package com.jasamedika.medifirst2000.dao.custom;

import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jasamedika.medifirst2000.dao.custom.base.impl.CoreDaoImpl;
import com.jasamedika.medifirst2000.entities.HasilPemeriksaanSwaPantauLimbahCair;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.DateUtil;

/**
 * Repository Custom class
 * 
 * @author Roberto
 */
@Repository
public class HasilPemeriksaanSwaPantauLimbahCairDaoCustomImpl extends CoreDaoImpl<HasilPemeriksaanSwaPantauLimbahCair> implements
		HasilPemeriksaanSwaPantauLimbahCairDaoCustom {

	public HasilPemeriksaanSwaPantauLimbahCairDaoCustomImpl() {
		super(HasilPemeriksaanSwaPantauLimbahCair.class);
	}

	@Override
	public List<Map<String,Object>> findList(int rowStart, int rowEnd, String sort, String dir, String dateStart,String dateEnd) {

		StringBuffer buffer = new StringBuffer();
		buffer.append(" select NEW map( ");
		//buffer.append("(elements(p.hasilPemeriksaanSwaDetail)) as data, ");
		buffer.append("coalesce(p.tanggal,null) as tanggal, ");
		buffer.append("coalesce(p.noRec,'-') as noRec, ");
		buffer.append("coalesce(p.keterangan,'-') as keterangan , ");
		buffer.append("coalesce(p.inletDebit,0.0) as inletDebit, ");
		buffer.append("coalesce(p.outletDebit,0.0) as outletDebit) from HasilPemeriksaanSwaPantauLimbahCair  p where p.noRec is not null ");
		if(CommonUtil.isNotNullOrEmpty(dateStart) && CommonUtil.isNotNullOrEmpty(dateEnd)){
			buffer.append("and date(p.tanggal) between :dateStart and :dateEnd ");
		}
		
		
		if (sort != "") {
			buffer.append("order by p." + sort + " " + dir);
		} else {
			buffer.append("order by p.noRec desc ");
		}
		Query query = em.createQuery(buffer.toString());
		if(CommonUtil.isNotNullOrEmpty(dateStart) && CommonUtil.isNotNullOrEmpty(dateEnd)){
			query.setParameter("dateStart",DateUtil.toDate(dateStart));
			query.setParameter("dateEnd", DateUtil.toDate(dateEnd));
		}
		
		
		query.setFirstResult(rowStart);
		query.setMaxResults(rowEnd);
		List<Map<String,Object>> list = query.getResultList();

		return list;
	}

	@Override
	public Integer findCount(String sort, String dateStart, String dateEnd) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(" select count(p.noRec) from HasilPemeriksaanSwaPantauLimbahCair p where p.noRec is not null ");
		if(CommonUtil.isNotNullOrEmpty(dateStart) && CommonUtil.isNotNullOrEmpty(dateEnd)){
			buffer.append("and date(p.tanggal) between :dateStart and :dateEnd ");
		}
		
		Query query = em.createQuery(buffer.toString());
		if(CommonUtil.isNotNullOrEmpty(dateStart) && CommonUtil.isNotNullOrEmpty(dateEnd)){
			query.setParameter("dateStart",DateUtil.toDate(dateStart));
			query.setParameter("dateEnd", DateUtil.toDate(dateEnd));
		}
		
		return ((Long) query.getSingleResult()).intValue();
	}



}
