package org.seasar.hibernate.dao.impl;

import java.lang.reflect.Method;

import net.sf.hibernate.Criteria;
import net.sf.hibernate.HibernateException;

import org.seasar.framework.beans.BeanDesc;
import org.seasar.framework.beans.factory.BeanDescFactory;
import org.seasar.hibernate.S2Session;
import org.seasar.hibernate.S2SessionFactory;
import org.seasar.hibernate.dao.criteria.CriteriaCommand;

/**
 * @author kenichi_okazaki
 */
public class AutoDtoQueryCommand extends AbstractAutoQueryCommand {

	BeanDesc dtoBeanDesc_;

	public AutoDtoQueryCommand(S2SessionFactory s2sessionFactory,
			Class beanClass, Method method) {
		super(s2sessionFactory, beanClass, method);
		dtoBeanDesc_ = BeanDescFactory
				.getBeanDesc(method.getParameterTypes()[0]);
	}

	protected Criteria getArgsCriteria(S2Session s2session, Object[] args)
			throws HibernateException {
		String[] argNames = getArgNames();
		Object dto = args[0];

		Criteria criteria = s2session.createCriteria(getBeanClass());

		for (int i = 0; i < argNames.length; i++) {
			String[] arg = argNames[i].split(" ");
			CriteriaCommand criteriaCommand = (CriteriaCommand) criteriaCommandList_.get(i);
			
			Object value = dtoBeanDesc_.getPropertyDesc( criteriaCommand.getDtoFieldName() ).getValue(dto);
			if( value != null ){
				criteria = criteriaCommand.getCriteria(criteria, value );
			}
		}
		return criteria;
	}
	
	public String[] getArgNames() {
		String[] args = super.getArgNames();
		
		if (args.length == 0) {
			//BeanDiscからプロパティを取得
			for( int i=0 ; i < dtoBeanDesc_.getPropertyDescSize();i++){
				args[i]=dtoBeanDesc_.getPropertyDesc(i).getPropertyName();
			}
		}
		return args;
	}
}