from src.db.database import Database
from src.logging.get_logger import get_logger
logger = get_logger("アーカイブ管理テーブル操作")

class JskultArchiveManager:
    _db : Database = None
    def __init__(self):
        self._db = Database.get_instance()

    def get_archive_manage(self):
        """対象テーブル、対象項目、対象年月、実行間隔（月）、前回対象年月、保存先を取得"""
        try:
            logger.info("処理開始：get_archive_manage")
            sql = """
                select
                    target_table
                    , filter_column
                    , filter_date
                    , run_interval_months
                    , prev_filter_date
                    , archive_storage 
                from
                    internal07.jskult_archive_manage;
            """
            self._db.connect()
            jskult_archive_manage_data = self._db.execute_select(sql)
            logger.info("処理終了：get_archive_manage")
            return jskult_archive_manage_data
        except Exception as e:
            logger.info("異常終了：get_archive_manage")
            raise
        finally:
            self._db.disconnect()

    def get_archive_data(self,target_table:str, filter_column:str, filter_date:str):
        """アーカイブするデータを取得"""
        try:
            logger.info("処理開始：get_archive_data")
            sql = f"""
                select
                    *
                from
                    src07.{target_table}
                where
                    str_to_date({filter_column},'%Y%m%d') <= :filter_date;
            """
            self._db.connect()
            parameter_dict = {'filter_date' : filter_date}
            target_table_data = self._db.execute_select(sql, parameter_dict)
            logger.info("処理終了：get_archive_data")
            return target_table_data
        except Exception as e:
            logger.info("異常終了：get_archive_data")
            raise
        finally:
            self._db.disconnect()

    def delete_archive_data(self, target_table:str, filter_column:str, filter_date:str):
        """アーカイブしたデータを削除"""
        try:
            logger.info("処理開始：delete_archive_data")
            sql = f"""
                delete from
                    src07.{target_table}
                where
                    str_to_date({filter_column},'%Y%m%d') <= :filter_date;
            """
            self._db.connect()
            self._db.begin()
            parameter_dict = {'filter_date' : filter_date}
            self._db.execute(sql, parameter_dict)
            self._db.commit()
            logger.info("処理終了：delete_archive_data")
            return
        except:
            self._db.rollback()
            logger.info("異常終了：delete_archive_data")
            raise
        finally:
            self._db.disconnect()

    def update_archive_manage(self, target_table:str):
        """アーカイブ管理テーブルの指定した対象テーブルのレコードを更新する"""
        try:
            logger.info("処理開始：update_archive_manage")
            sql = f"""
                update internal07.jskult_archive_manage 
                set
                    prev_filter_date = filter_date
                    , filter_date = LAST_DAY( 
                        DATE_ADD(filter_date, INTERVAL run_interval_months MONTH)
                    ) 
                    , upd_user = CURRENT_USER()
                    , upd_date = NOW() 
                where
                    target_table = '{target_table}';
            """
            self._db.connect()
            self._db.begin()
            self._db.execute(sql)
            self._db.commit()
            logger.info("処理終了：update_archive_manage")
            return
        except:
            self._db.rollback()
            logger.info("異常終了：update_archive_manage")
            raise
        finally:
            self._db.disconnect()
