package com.tarena.oss.pricing.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.pricing.pojo.Pricing;
import com.tarena.oss.util.PageParameter;

public class PricingMgmtDAOByHibernate extends HibernateDaoSupport implements PricingMgmtDAO {

	public void deletePricing(Pricing p) {
		this.getHibernateTemplate().delete(p);
	}

	public void insertPricing(Pricing p) {
		this.getHibernateTemplate().save(p);
	}

	public boolean isUsed(Integer id) {
		// TODO Auto-generated method stub
		return false;
	}

	public Pricing queryPricing(Integer id) {
		return  (Pricing) this.getHibernateTemplate().find("from Pricing p where p.id="+id).get(0);
	}

	public Collection<Pricing> queryPricings() {
		return this.getHibernateTemplate().find("from Pricing p");
	}

	public Collection<Pricing> queryPricings(String cond) {
		System.out.println(cond+"===cond===");
		return this.getHibernateTemplate().find("from Pricing p where 1=1"+ cond);
	}

	public void updatePricing(Pricing p) {
		this.getHibernateTemplate().update(p);
	}

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

	public int queryPricingCnt() {
		// TODO Auto-generated method stub
		return 0;
	}

	public Collection<Pricing> queryPricings(int currentPage) {
		// TODO Auto-generated method stub
		return null;
	}

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

}
