package com.jasamedika.medifirst2000.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.dao.RekananDao;
import com.jasamedika.medifirst2000.dao.custom.RekananDaoCustom;
import com.jasamedika.medifirst2000.entities.JenisRekanan;
import com.jasamedika.medifirst2000.entities.Rekanan;
import com.jasamedika.medifirst2000.service.RekananService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.vo.JenisRekananVO;
import com.jasamedika.medifirst2000.vo.RekananVO;


/**
 * 
 * @author adik
 */
@Service("rekananService")
public class RekananServiceImpl implements RekananService{
	
	@Autowired
	private BaseConverterImpl<RekananVO,Rekanan> rekananConvereter;
	
	@Autowired
	private RekananDaoCustom rekananDaoCustom;

	@Autowired
	private BaseConverterImpl<JenisRekananVO,JenisRekanan> jenisRekananConvereter;

	
	@Autowired
	private RekananDao rekananDao;

	@Override
	public Map<String, Object> saveRekanan(RekananVO vo) {
		Rekanan rekanan=rekananConvereter.transferVOToModel(vo, new Rekanan());
		if(CommonUtil.isNotNullOrEmpty(vo.getJenisRekanan())){
			rekanan.setJenisRekanan(jenisRekananConvereter.transferVOToModel(vo.getJenisRekanan(), new JenisRekanan()));
		}
		rekananDao.save(rekanan);
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("data",rekanan.getId());
		return result;
	}

	
	@Override
	@Transactional(readOnly=false)
	public Map<String, Object> listRekanan(Integer page, Integer limit, String sort, String dir, Integer rekananId,Integer jenisRekananId) {

		int totalRow = rekananDaoCustom.listRuanganCount(rekananId,jenisRekananId);
		int totalPages = 0;

		int pageRequested = page;

		if (totalRow > 0) {
			totalPages = (int) Math.ceil((double) totalRow / (double) limit);
		} else {
			totalPages = 0;
		}

		if (pageRequested > totalPages)
			pageRequested = totalPages;
		int rowStart = pageRequested * limit - limit;
		if (rowStart < 0) {
			rowStart = 0;
		}
		int rowEnd = limit;
		Map<String, Object> result=new HashMap<String,Object>();
		result.put("data", rekananDaoCustom.listRuangan(page,limit,sort,dir,rekananId,jenisRekananId));
		result.put("totalPages", totalPages);
		result.put("totalRow", totalRow);
		return result;
		
	
	}
}

