package com.tarena.oss.rights.dao;

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

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.rights.pojo.Role;
import com.tarena.oss.util.PageParameter;

public class RoleMgmtDAOByHibernate extends HibernateDaoSupport implements
		RoleMgmtDAO {

	public void deleteRole(Role r) {
		this.getHibernateTemplate().delete(r);
	}

	public void insertRote(Role r) {
		this.getHibernateTemplate().save(r);
	}

	public Role queryRole(Integer id) {
		return (Role) this.getHibernateTemplate().find("from Role r where r.id="+id).get(0);
	}

	public Collection<Role> queryRole(int currentPage) {
		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 Role r");
				qry.setFirstResult(startRow);
				qry.setMaxResults(PageParameter.CNT_EACH_PAGE);
				return qry.list();
			}
			
		});
	}

	public Collection<Role> queryRole(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 Role r where 1=1 "+qryStr);
				qry.setFirstResult(startRow);
				qry.setMaxResults(PageParameter.CNT_EACH_PAGE);
				return qry.list();
			}
			
		});
	}

	public int queryRoleCnt() {
		Integer cnt=(Integer)this.getHibernateTemplate().find("select count(*) from Role r").get(0);
		return cnt.intValue();
	}

	public int queryRoleCnt(String cond) {
		Integer cnt=(Integer)this.getHibernateTemplate().find("select count(*) from Role r where 1=1 "+cond).get(0);
		return cnt.intValue();
	}

	public void updateRole(Role r) {
		this.getHibernateTemplate().update(r);
	}

}
