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


@Repository
public class MapPaketToProdukDaoCustomImpl extends CoreDaoImpl<MapPaketToProduk> implements
MapPaketToProdukDaoCustom{
	
	public MapPaketToProdukDaoCustomImpl() {
		super(MapPaketToProduk.class);
	}

	@Override
	public Integer findCountMapPaketToProduk(String namaPaket) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("select count(a) ");
		buffer.append("from MapPaketToProduk a ");
		buffer.append("left join a.paket b ");
		buffer.append("left join a.produk c ");
		buffer.append("left join a.satuan d ");
		if(CommonUtil.isNotNullOrEmpty(namaPaket)){
			buffer.append("where b.namaPaket =:namaPaket ");
		}
		Query query = em.createQuery(buffer.toString());
		if(CommonUtil.isNotNullOrEmpty(namaPaket)){
			query.setParameter("namaPaket", namaPaket);
		}
		return ((Long) query.getSingleResult()).intValue();
	}
	
	@Override
	public List<Map<String, Object>> findListMapPaketToProduk(int rowStart, int rowEnd, String sort, String dir,String namaPaket) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("select NEW Map ( ");
		buffer.append("a.id as id, ");
		buffer.append("b.namaPaket as namaPaket, ");
		buffer.append("c.namaProduk as namaAlat, ");
		buffer.append("d.satuanStandar as satuan, ");		
		buffer.append("a.qtyProduk as qtyProduk) ");
		buffer.append("from MapPaketToProduk a ");
		buffer.append("left join a.paket b ");
		buffer.append("left join a.produk c ");
		buffer.append("left join a.satuan d ");
		buffer.append("where (a.statusEnabled is null or a.statusEnabled is true) ");		
		if(CommonUtil.isNotNullOrEmpty(namaPaket)){
			buffer.append("and b.namaPaket =:namaPaket ");
		}
		if (sort != "") {
			buffer.append("order by " + sort + " " + dir);
		} else {
			buffer.append("order by a.id desc ");
		}
		Query query = em.createQuery(buffer.toString());
		if(CommonUtil.isNotNullOrEmpty(namaPaket)){
			query.setParameter("namaPaket", namaPaket);
		}
		query.setFirstResult(rowStart);
		query.setMaxResults(rowEnd);
		List<Map<String,Object>> list = query.getResultList();

		return list;
	}
	
	

}
