from src.logging.get_logger import get_logger
from src.model.db.user_master import UserMasterModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('ユーザー取得')


class UserMasterRepository(BaseRepository):

    def to_jst(self):
        self._database.to_jst()

    def begin(self):
        self._database.begin()

    def commit(self):
        self._database.commit()

    def rollback(self):
        self._database.rollback()

    FETCH_SQL = """\
    SELECT
        *
    FROM
        src05.user_mst
    WHERE
        user_id = :user_id\
    """

    def fetch_one(self, parameter: dict) -> UserMasterModel:
        try:
            query = self.FETCH_SQL
            result = self._database.execute_select(query, parameter)
            models = [UserMasterModel(**r) for r in result]
            if len(models) == 0:
                return None
            return models[0]
        except Exception as e:
            logger.exception(f"DB Error : Exception={e}")
            raise e

    def increase_login_failed_count(self, parameter: dict) -> UserMasterModel:
        try:
            query = """\
            UPDATE
                src05.user_mst
            SET
                mntuser_login_failed_cnt =
                    CASE
                        WHEN
                            DATE(mntuser_last_login_failed_datetime) = DATE(CURRENT_TIMESTAMP())
                        THEN
                            mntuser_login_failed_cnt + 1
                        ELSE
                            1
                    END,
                mntuser_last_login_failed_datetime = CURRENT_TIMESTAMP()
            WHERE
                user_id = :user_id
                AND
                mntuser_flg = 1;\
            """
            self._database.execute(query, parameter)
        except Exception as e:
            logger.exception(f"DB Error : Exception={e}")
            raise e

    def disable_mnt_user(self, parameter: dict) -> UserMasterModel:
        try:
            query = """\
            UPDATE
                src05.user_mst
            SET
                enabled_flg = 'N'
            WHERE
                user_id = :user_id
                AND
                mntuser_flg = 1\
            """
            self._database.execute(query, parameter)
        except Exception as e:
            logger.exception(f"DB Error : Exception={e}")
            raise e
