package com.jasamedika.medifirst2000.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.jasamedika.medifirst2000.dao.JadwalOperasiDao;
import com.jasamedika.medifirst2000.entities.JadwalOperasi;
import com.jasamedika.medifirst2000.service.JadwalOperasiService;
import com.jasamedika.medifirst2000.util.CommonUtil;

/**
 * @author salmanoe
 * @since Feb 21, 2023
 */
@Service("jadwalOperasiService")
public class JadwalOperasiServiceImpl implements JadwalOperasiService {
	@Autowired
	private JadwalOperasiDao jadwalOperasiDao;

	@Override
	public List<Map<String, Object>> jadwalOperasiByPeriode(LocalDate start, LocalDate end) {
		LocalDateTime startDateTime = LocalDateTime.of(start, LocalTime.MIN);
		Date tglAwal = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
		LocalDateTime endDateTime = LocalDateTime.of(end, LocalTime.MAX);
		Date tglAkhir = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
		List<JadwalOperasi> listOperasi = jadwalOperasiDao.findAllByPeriod(tglAwal, tglAkhir);
		return jadwalOperasi(listOperasi);
	}

	@Override
	public List<Map<String, Object>> jadwalOperasiByPasien(String noBpjs) {
		List<JadwalOperasi> listOperasi = jadwalOperasiDao.findAllByPasien(noBpjs);
		return jadwalOperasi(listOperasi);
	}

	private List<Map<String, Object>> jadwalOperasi(List<JadwalOperasi> listOperasi) {
		Date now = new Date();
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		listOperasi.forEach(o -> {
			Map<String, Object> operasi = new HashMap<>();
			operasi.put("noRegistrasi", o.getAntrean().getPasienDaftar().getNoRegistrasi());
			operasi.put("tglOperasi", o.getTglOperasi());
			operasi.put("jenisTindakan", o.getTindakan());
			operasi.put("ruanganId", CommonUtil.isNotNullOrEmpty(o.getRuangan()) ? o.getRuangan().getId() : null);
			operasi.put("terlaksana", false);
			if (CommonUtil.isNotNullOrEmpty(o.getTglOperasi())
					&& (o.getTglOperasi().before(now) || o.getTglOperasi().equals(now)))
				operasi.put("terlaksana", true);
			operasi.put("noBpjs", CommonUtil.isNotNullOrEmpty(o.getPasien())
					? (CommonUtil.isNotNullOrEmpty(o.getPasien().getNoBpjs()) ? o.getPasien().getNoBpjs() : '-') : '-');
			operasi.put("lastUpdate", o.getLastUpdate());
			result.add(operasi);
		});
		return result;
	}
}
