from src.repositories.base_repository import BaseRepository
from src.model.db.master_mente_count import MasterMenteCountModel
from src.logging.get_logger import get_logger

logger = get_logger('従業員マスタ')


class EmpMasterRepository(BaseRepository):

    FETCH_COUNT_SQL = """\
        SELECT
            COUNT(*) AS count
        FROM
            src05.emp
        WHERE
                emp.emp_cd = :emp_cd
            AND str_to_date(emp.start_date, '%Y%m%d') <= str_to_date(:start_work_date, '%Y%m%d')
            AND str_to_date(:start_work_date, '%Y%m%d') <= str_to_date(emp.end_date ,'%Y%m%d')
    """

    def fetch_count(self, emp_cd, start_work_date) -> MasterMenteCountModel:
        try:
            query = self.FETCH_COUNT_SQL
            result = self._database.execute_select(query, {'emp_cd': emp_cd, 'start_work_date': start_work_date})
            models = [MasterMenteCountModel(**r) for r in result]
            if len(models) == 0:
                return 0
            return models[0].count
        except Exception as e:
            logger.exception(f"DB Error : Exception={e.args}")
            raise e
