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

public class RightsMgmtDAOByHibernate extends HibernateDaoSupport implements
		RightsMgmtDAO {

	public void deleteRights(Rights r) {
		this.getHibernateTemplate().delete(r);
	}

	public void insertRights(Rights r) {
		this.getHibernateTemplate().save(r);
	}

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

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

	public Collection<Rights> queryRights(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 Rights r");
				qry.setFirstResult(startRow);
				qry.setMaxResults(PageParameter.CNT_EACH_PAGE);
				return qry.list();
			}
			
		});
	}

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

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

	public void updateRights(Rights r) {
		this.getHibernateTemplate().update(r);
	}

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

	public Operation queryOperation(Integer id) {
		return (Operation) this.getHibernateTemplate().find("from Operation o where o.id="+id).get(0);
	}

	public Collection<Rights> queryRights() {
		return this.getHibernateTemplate().find("from Rights r");
	}

	public Collection<Module> queryModules() {
		return this.getHibernateTemplate().find("from Module m");
	}

	public Collection<Operation> queryOperation() {
		return this.getHibernateTemplate().find("from Operation");
	}

}
