package com.ffii.lioner.modules.lioner.pdf.service;

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

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ffii.core.exception.NotFoundException;
import com.ffii.core.exception.UnprocessableEntityException;
import com.ffii.core.support.AbstractBaseEntityService;
import com.ffii.core.support.JdbcDao;
import com.ffii.core.utils.BeanUtils;
import com.ffii.lioner.modules.common.service.AuditLogService;
import com.ffii.lioner.modules.lioner.pdf.entity.Consultant;
import com.ffii.lioner.modules.lioner.pdf.req.UpdateConsultantReq;
import com.ffii.lioner.modules.lioner.pdf.entity.ConsultantRepository;

@Service
public class ConsultantService extends AbstractBaseEntityService<Consultant, Long, ConsultantRepository> {

	private AuditLogService auditLogService;
	
	public ConsultantService(JdbcDao jdbcDao, ConsultantRepository repository, AuditLogService auditLogService) {
		super(jdbcDao, repository);
		this.auditLogService = auditLogService;
	}

	public Map<String, Object> saveOrUpdate(UpdateConsultantReq req) {
		Consultant instance;
		// List<SubDivision> onUsingIdList = new ArrayList<SubDivision>();
		if(req.getId() == null)
			req.setId(-1L);

		if (req.getId() > 0){
			instance = find(req.getId()).get();
			// onUsingIdList = this.getSelectedSubDivisionList(req.getId());
		}
		else {
			instance = new Consultant();
		}

		BeanUtils.copyProperties(req,instance);
		instance = save(instance);
		
		return Map.of(
			"id", instance.getId()
		);
	}

	public List<Map<String,Object>> list(Map<String, Object> args){
		StringBuilder sql = new StringBuilder("SELECT"
			+ " c.id, "
			+ " c.name, "
			+ " c.created, "
			+ " c.modified "
			+ " FROM consultant c "
			+ " WHERE c.deleted = FALSE "
		);

		if (args != null) {
			if (args.containsKey("name")) 
				sql.append(" AND c.name LIKE :name ");
			if (args.containsKey("createDateFrom")) 
				sql.append(" AND c.created >= :createDateFrom ");
			if (args.containsKey("createDateTo")) 
				sql.append(" AND c.created <= :createDateTo ");
		}
		sql.append(" ORDER BY c.id asc ");

		return jdbcDao.queryForList(sql.toString(), args);
	}

	public Map<String, Object> loadConsultant(Long id) {
		String sql = "SELECT"
			+ " c.id, "
			+ " c.name "
			+ " FROM consultant c "
			+ " WHERE c.deleted = FALSE "
			+ " AND c.id = :id "
        ;
        return jdbcDao.queryForMap(sql, Map.of("id", id)).orElseThrow(NotFoundException::new);
    }
}