package com.tarena.oss.admin.dao;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tarena.oss.admin.pojo.Admin;
import com.tarena.oss.util.PageParameter;

public class AdminMgmtDAOByHibernate extends HibernateDaoSupport implements
		AdminMgmtDAO {

	public Admin validate(String userName, String password) {
		List<Admin> admins=this.getHibernateTemplate().
		find("from Admin a where a.loginname=? and a.loginpassword=?", new Object[]{userName, password});
		if(admins==null || admins.size()==0)
			return  null;
		else
			return admins.get(0);
	}

	public void deleteAdmin(Admin a) {
		this.getHibernateTemplate().delete(a);
		
	}

	public void insertAdmin(Admin a) {
		this.getHibernateTemplate().save(a);
		
	}

	public Admin queryadmin(Integer id) {
		return  (Admin) this.getHibernateTemplate().find("from Admin a where a.id= "+id).get(0);
	}

	public Collection<Admin> queryadmins() {
		return this.getHibernateTemplate().find("from Admin a");
	}

	public Collection<Admin> queryadmins(String cond) {
		return this.getHibernateTemplate().find("from Admin a where 1=1"+cond);
	}

	public void updateAdmin(Admin a) {
		this.getHibernateTemplate().update(a);
		
	}

	public Collection<Admin> queryadmins(String cond, int currentPage) {
		final String qryStr = cond;
		final int startRow = (currentPage - 1) * PageParameter.CNT_EACH_PAGE;
		
		return this.getHibernateTemplate().executeFind(new HibernateCallback(){

			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query qry = session.createQuery("from Admin a where 1=1 " + qryStr);
				qry.setFirstResult(startRow);
				qry.setMaxResults(PageParameter.CNT_EACH_PAGE);
				return qry.list();
			}
			
		});
	}

	public int queryPricingCnt(String cond) {
		Integer value =(Integer) this.getHibernateTemplate().find("select count(*) from Admin a where 1=1 "+cond).get(0);
		return value.intValue();
	}

}
