from src.logging.get_logger import get_logger
from src.model.db.ultmarc_specialist_license import \
    UltmarcSpecialistLicenseDBModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('COM_専門医資格取得')


class UltmarcSpecialistLicenseRepository(BaseRepository):

    FETCH_SQL = """\
        SELECT
            com_specialist_license.specialist_cd, com_specialist_license.specialist_license_name
        FROM src05.com_dr
        LEFT JOIN src05.com_sp_field ON com_dr.dcf_pcf_dr_cd = com_sp_field.dcf_pcf_dr_cd
        LEFT JOIN src05.com_specialist_license ON com_sp_field.specialist_cd = com_specialist_license.specialist_cd
        WHERE com_dr.dcf_pcf_dr_cd = :id
        ORDER BY com_specialist_license.specialist_cd
    """

    def fetch_many(self, id) -> UltmarcSpecialistLicenseDBModel:
        try:
            self._database.connect()
            query = self.FETCH_SQL
            result = self._database.execute_select(query, {'id': id})
            models = [UltmarcSpecialistLicenseDBModel(**r) for r in result]
            if len(models) == 0:
                return None
            return models
        except Exception as e:
            logger.exception(f"DB Error : Exception={e.args}")
            raise e
        finally:
            self._database.disconnect()
