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 AbstractQueryHibernateCommand extends AbstractHibernateCommand {

	private Class beanClass_;
	private Method method_;
	
	private String[] argNames_;
	
	/**
	 * @param s2sessionFactory
	 */
	public AbstractQueryHibernateCommand(S2SessionFactory s2sessionFactory,Class beanClass,Method method) {
		super(s2sessionFactory);
		beanClass_ = beanClass;
		method_ = method;
	}

	protected List queryExecute(Query query,Object[] args ){

		try {
			for (int i = 0; i < argNames_.length; ++i) {
				if (args[i] != null) {
					if (argNames_[i].equals("firstResult") == true) {
						query.setFirstResult(((Integer) args[i]).intValue());
				
					} else if (argNames_[i].equals("maxResults") == true) {
						query.setMaxResults(((Integer) args[i]).intValue());

					} else {
						if( args[i] instanceof List){
							query.setParameterList(argNames_[i], (List)args[i]);

						}else{
							query.setParameter(argNames_[i], args[i]);
						}
					}
				}
			}

			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 get
	
	public Method getMethod() {
		return method_;
	}

	public void setMethod(Method method) {
		method_ = method;
	}
	
	public String[] getArgNames() {
		return argNames_;
	}

	public void setArgNames(String[] argNames) {
		argNames_ = argNames;
	}

	public Class getBeanClass() {
		return beanClass_;
	}

	public void setBeanClass(Class beanClass) {
		beanClass_ = beanClass;
	}
}
