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.LaporanUjiHasil;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.DateUtil;

/**
 * Repository Custom class
 * 
 * @author Roberto
 */
@Repository
public class LaporanUjiHasilDaoCustomImpl extends CoreDaoImpl<LaporanUjiHasil> implements
		LaporanUjiHasilDaoCustom {

	public LaporanUjiHasilDaoCustomImpl() {
		super(LaporanUjiHasil.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( coalesce(p.noRec, '-') as noRec,  ");
		buffer.append(" coalesce(p.uraianContoh, '-') as uraianContoh, ");
		buffer.append(" coalesce(p.tanggalPenerimaanContoh, null) as tanggalPenerimaanContoh, ");
		buffer.append(" coalesce(p.tanggalPengujianContohFrom, null) as tanggalPengujianContohFrom, ");
		buffer.append(" coalesce(p.tanggalPengujianContohTo, null) as tanggalPengujianContohTo, ");
		buffer.append(" coalesce(r.namaRekanan, '-') as namaRekanan) ");
		buffer.append(" from LaporanUjiHasil p left join p.rekanan r where p.noRec is not null ");
		if(CommonUtil.isNotNullOrEmpty(dateStart) && CommonUtil.isNotNullOrEmpty(dateEnd)){
			buffer.append("and date(p.tanggalPenerimaanContoh) between :dateStart and :dateEnd ");
		}
		
		
		if (sort != "") {
			buffer.append("order by p." + sort + " " + dir);
		} else {
			buffer.append("order by 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) ");
		buffer.append(" from LaporanUjiHasil p left join p.rekanan r where p.noRec is not null ");
		if(CommonUtil.isNotNullOrEmpty(dateStart) && CommonUtil.isNotNullOrEmpty(dateEnd)){
			buffer.append("and date(p.tanggalPenerimaanContoh) 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();
	}



}
