package com.ffii.core.department.service;

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

import org.springframework.stereotype.Service;

import com.ffii.core.department.dao.DepartmentDao;
import com.ffii.core.department.entity.Department;
import com.ffii.core.support.AbstractBaseEntityService;
import com.ffii.core.support.JdbcDao;
import com.ffii.core.utils.Params;

@Service
public class DepartmentService extends AbstractBaseEntityService<Department, Integer, DepartmentDao> {

  public DepartmentService(JdbcDao jdbcDao, DepartmentDao dao) {
    super(jdbcDao, dao);
  }

  public List<Map<String, Object>> searchForCombo(Map<String, Object> args) {
    StringBuilder sql = new StringBuilder("SELECT"
        + " d.id,"
        + " d.name"
        + " FROM department d"
        + " WHERE d.deleted = 0");

    if (args != null) {
      if (args.containsKey(Params.QUERY))
        sql.append(" AND d.name LIKE :query");

      if (args.containsKey(Params.ID))
        sql.append(" AND d.id = :id");
      if (args.containsKey(Params.NAME))
        sql.append(" AND d.name LIKE :name");

    }

    sql.append(" ORDER BY d.name");

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

  public List<Map<String, Object>> search(Map<String, Object> args) {

    StringBuilder sql = new StringBuilder("SELECT"
        + " d.*"
        + " FROM department d"
        + " WHERE d.deleted = 0");

    if (args != null) {
      if (args.containsKey(Params.QUERY))
        sql.append(" AND d.name LIKE :query");

      if (args.containsKey(Params.ID))
        sql.append(" AND d.id = :id");
      if (args.containsKey(Params.NAME))
        sql.append(" AND d.name LIKE :name");
      if (args.containsKey("description"))
        sql.append(" AND d.description LIKE :description");
    }

    sql.append(" ORDER BY d.name");

    if (args != null) {
      if (args.containsKey(Params.START) && args.containsKey(Params.LIMIT))
        sql.append(" LIMIT :start, :limit");
    }

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

  public int searchTotalCount(Map<String, Object> args) {
    StringBuilder sql = new StringBuilder("SELECT"
        + " COUNT(*) AS count"
        + " FROM department d"
        + " WHERE d.deleted = FALSE");

    if (args != null) {
      if (args.containsKey(Params.NAME))
        sql.append(" AND ( d.name LIKE :name OR d.description LIKE :name)");
    }

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

  public String getDeptNameById(Integer deptId) {
    return jdbcDao.queryForString("SELECT"
        + " d.name"
        + " FROM department d"
        + " WHERE d.id = "
        + deptId);
  }

  public boolean existsEqType(int id) {
    return jdbcDao.queryForBoolean(" select exists"
        + " (select 1 from equipment_type et where deleted = 0 and caseOwnerId = :id)", Map.of("id", id));
  }
}
