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

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

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

	protected Class getBeanClass() {
		return beanClass_;
	}

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