package com.jasamedika.medifirst2000.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.jasamedika.medifirst2000.converter.KonversiSatuanConverter;
import com.jasamedika.medifirst2000.dao.KonversiSatuanDao;
import com.jasamedika.medifirst2000.entities.KonversiSatuan;
import com.jasamedika.medifirst2000.service.KonversiSatuanService;
import com.jasamedika.medifirst2000.vo.KonversiSatuanVO;

@Service("KonversiSatuanService")
public class KonversiSatuanServiceImpl extends BaseVoServiceImpl implements KonversiSatuanService {
	
	@Autowired
	private KonversiSatuanDao konversiSatuanDao;
	
	@Autowired
	private KonversiSatuanConverter converter;

	@Override
	public Map<String, Object> save(KonversiSatuanVO vo) {
		KonversiSatuan model = converter.transferVOToModel(vo, new KonversiSatuan());
		
		konversiSatuanDao.save(model);
		Map<String, Object> result = new HashMap<>();
		result.put("norec", model.getNoRec());
		return result;
	}

	@Override
	public Map<String, Object> get(String norec) {
		KonversiSatuan data = konversiSatuanDao.findOne(norec);
		
		KonversiSatuanVO vo = converter.transferModelToVO(data, new KonversiSatuanVO());
		
		Map<String, Object> result = new HashMap<>();
		result.put("data", vo);
		return result;
	}

	@Override
	public Map<String, Object> list(Integer page, Integer limit, String sort, String dir) {
		Direction direction = null;
		if (dir.equalsIgnoreCase("asc")) {
			direction = Direction.ASC;
		} else {
			direction = Direction.DESC;
		}
		
		Pageable pageable = new PageRequest(page, limit, direction, sort);
		Page<KonversiSatuan> resultPage = konversiSatuanDao.findAll(pageable);
		List<KonversiSatuan> data = resultPage.getContent();
		return constructMapReturn(data, resultPage.getTotalElements(), resultPage.getTotalPages());
	}

	@Override
	public Map<String, Object> listByProduk(Integer produkId) {
		List<KonversiSatuan> result = konversiSatuanDao.findByProdukId(produkId);
		return constructMapReturn(result, result.size(), result.size());
	}

	@Override
	public Map<String, Object> update(KonversiSatuanVO vo) {
		KonversiSatuan model = konversiSatuanDao.findOne(vo.getNoRec());
		Map<String, Object> result = new HashMap<>();
		if (model != null) {
			model.getProduk().setId(vo.getProduk().getId());
			model.getSatuanStandarAsal().setId(vo.getSatuanStandarAsal().getId());
			model.getSatuanStandarTujuan().setId(vo.getSatuanStandarTujuan().getId());
			model.setNilaiKonversi(vo.getNilaiKonversi());
			konversiSatuanDao.save(model);
			result.put("noRec", model.getNoRec());
		} else {
			result.put("noRec", null);
		}
		
		return result;
	}

}
