package org.seasar.dao.impl;

import javax.sql.DataSource;

import org.seasar.dao.BeanMetaData;
import org.seasar.extension.jdbc.PropertyType;
import org.seasar.framework.beans.PropertyDesc;
import org.seasar.framework.util.IntegerConversionUtil;

/**
 * @author higa
 *  
 */
public class UpdateAutoHandler extends AbstractAutoHandler {

	public UpdateAutoHandler(DataSource dataSource, BeanMetaData beanMetaData) {
		super(dataSource, beanMetaData);
	}

	protected void setupSql() {
		setSql(getBeanMetaData().getAutoUpdateSql());
	}

	protected Object[] getBindVariables(Object bean) {
		return getBeanMetaData().getAutoUpdateBindVariables(bean);
	}

	protected void postUpdateBean(Object bean, Object[] bindVariables) {
		BeanMetaData bmd = getBeanMetaData();
		if (bmd.hasVersionNoPropertyType()) {
			PropertyDesc pd = bmd.getVersionNoPropertyType().getPropertyDesc();
			Object value = pd.getValue(bean);
			int intValue = IntegerConversionUtil.toPrimitiveInt(value) + 1;
			pd.setValue(bean, new Integer(intValue));
		}
		if (bmd.hasTimestampPropertyType()) {
			for (int i = 0; i < bmd.getPropertyTypeSize(); ++i) {
				PropertyType pt = bmd.getPropertyType(i);
				if (pt.isPersistent()
						&& !pt.isPrimaryKey()
						&& !pt.getPropertyName().equals(
								BeanMetaData.VERSION_NO_PROPERTY_NAME)
						&& pt.getPropertyName().equalsIgnoreCase(
								BeanMetaData.TIMESTAMP_PROPERTY_NAME)) {

					PropertyDesc pd = pt.getPropertyDesc();
					pd.setValue(bean, bindVariables[i]);
					return;
				}
			}
		}
	}
}