package org.seasar.hibernate.dao.impl;

import java.util.List;
import java.lang.reflect.Method;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;

import org.seasar.hibernate.HibernateRuntimeException;
import org.seasar.hibernate.S2SessionFactory;

/**
 * @author kenichi_okazaki
 *
 */
public abstract class AbstractHQLHibernateCommand extends AbstractQueryHibernateCommand {

	/**
	 * @param s2sessionFactory
	 */
	public AbstractHQLHibernateCommand(S2SessionFactory s2sessionFactory,Class beanClass,Method method) {
		super(s2sessionFactory,beanClass,method);

	}

	protected List queryExecute(Query query,Object[] args ){
		String[] argNames ;
//		BeanDesc dtoBeanDesc = getDtoBeanDesc();
		ArgsMetaData argsMeta = getArgsMeta();
//		if(dtoBeanDesc==null){
			argNames = argsMeta.getArgNames();
//		}else{
//		}
			
			
		try {
//			for (int i = 0; i < getValueLength( argNames ); ++i) {
				for (int i = 0; i < argsMeta.getArgsCount(); ++i) {
				
//				Object value = args[i];
				Object value = argsMeta.getValue( args, i);
				String name = argsMeta.getArgument(i).getFieldName();
				if (value != null) {
					if (name.equals("firstResult") == true) {
						query.setFirstResult(((Integer) value).intValue());
				
					} else if (name.equals("maxResults") == true) {
						query.setMaxResults(((Integer) value).intValue());

					} else {
						if( value instanceof List){
							query.setParameterList(name, (List)value);

						}else{
							query.setParameter(name, value);
						}
					}
				}
			}

			return query.list();

		} catch (HibernateException ex) {
			throw new HibernateRuntimeException(ex);
		}
	}
	
	protected Object getReturnObject(Method method,List ret){
		if (method.getReturnType().isAssignableFrom(List.class)) {
			return ret;
		} else  {
			if(ret == null || ret.size() == 0){
				return null;
			} else {
				return ret.get(0);
			}
		}
	}
/*	
	private Object getValue(String[] argNames ,Object[] args,int i){
//		if(argNames.length=0 && args=1){
		BeanDesc dtoBeanDesc = getDtoBeanDesc();
		if(dtoBeanDesc==null){
			return args[i];
		}else{
			return dtoBeanDesc.getPropertyDesc( argNames[i] ).getValue(args[0]);
		}
	};
	
	private String getName(String[] argNames ,int i){
//		if(argNames.length=0 && args=1){
		BeanDesc dtoBeanDesc = getDtoBeanDesc();
		if(dtoBeanDesc==null){
			return argNames[i];
		}else{
			return dtoBeanDesc.getPropertyDesc(i ).getPropertyName();
		}
	};
	
	private int getValueLength(String[] argNames ){
		BeanDesc dtoBeanDesc = getDtoBeanDesc();
		if(dtoBeanDesc==null){
			return argNames.length;
		}else{
			return dtoBeanDesc.getPropertyDescSize();
		}
	}	
	*/

}
