import os.path as path
from datetime import datetime

import pytest

from src.batch.common.batch_context import BatchContext
from src.batch.ultmarc.utmp_tables.table_mapper.concrete import com_prefc_med_sojourn_ope_mapper
from src.db.database import Database
from tests.testing_utility import (assert_table_results,
                                   create_db_data_from_csv,
                                   create_delete_sql_with_parameter,
                                   create_insert_sql_with_parameter,
                                   create_ultmarc_table_mapper_sut,
                                   create_ultmarc_test_data_from_csv)


class TestComPrefcMedSojournOpeMapper:
    """レイアウト区分135: COM_都道府県医療機能情報(短期滞在手術)"""

    db: Database
    batch_context: BatchContext
    test_file_path: str = path.dirname(__file__)

    @pytest.fixture(autouse=True, scope='function')
    def pre_test(self, database: Database):
        """テスト実行前後処理"""
        self.batch_context = BatchContext.get_instance()
        # setup
        self.db = database
        self.db.connect()
        self.db.begin()

        # testing
        yield

        # teardown
        self.db.rollback()
        self.db.disconnect()

    def test_insert_record(self):
        """
        Cases:
            COM_都道府県医療機能情報(短期滞在手術)テーブルにレコードを登録する
        Arranges:
            - CSVデータを用意し、読み込む
            - 追加対象となるレコードを削除する
        Expects:
            - 登録内容が期待値と一致すること
        """

        # Arrange
        # 処理日設定
        self.batch_context.syor_date = datetime.strftime(datetime.now(), '%Y/%m/%d')
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_prefc_med_sojourn_ope_insert.csv'))
        # 一旦全データをDBから削除
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_prefc_med_sojourn_ope', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)

        # Act
        for line_number, line in enumerate(test_dat_file, start=1):
            sut: com_prefc_med_sojourn_ope_mapper.ComPrefcMedSojournOpeMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_prefc_med_sojourn_ope_mapper.ComPrefcMedSojournOpeMapper, f'{line_number}行目:マッパークラスが期通りか'
            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_prefc_med_sojourn_ope_insert.csv'))
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_data_list]
        primary_keys_cos_surgery_code = [{'cos_surgery_code': columns['cos_surgery_code']} for columns in expect_data_list]
        actual_data_list = []
        sp_field_select_sql = """\
        SELECT * FROM src05.com_prefc_med_sojourn_ope
        WHERE
            dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND
            cos_surgery_code = :cos_surgery_code
        """
        for param_dcf_dsf_inst_cd, param_cos_surgery_code in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_cos_surgery_code):
            sp_field_data = self.db.execute_select(
                sp_field_select_sql,
                {**param_dcf_dsf_inst_cd, **param_cos_surgery_code})
            assert len(sp_field_data) == 1, '1件取得できていること'
            actual_data_list.append(sp_field_data[0])

        # 期待値検査
        ignore_columns = ['regist_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_data_list, expect_data_list, ignore_col_name=ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_data_list, expect_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in ignore_columns:
                    assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

    def test_update_record(self):
        """
        Cases:
            COM_都道府県医療機能情報(短期滞在手術)テーブルのレコードを更新する
        Arranges:
            - CSVデータを用意し、読み込む
            - 更新対象となるレコードを登録する
        Expects:
            - 登録内容が期待値と一致すること
        """

        # Arrange
        # 処理日設定
        self.batch_context.syor_date = datetime.strftime(datetime.now(), '%Y/%m/%d')
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_prefc_med_sojourn_ope_update.csv'))
        # 一旦全データをDBから削除
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_prefc_med_sojourn_ope', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # テストデータをDBに登録
        # DBデータを読み込む
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_prefc_med_sojourn_ope_before_update.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_prefc_med_sojourn_ope',
                test_data.keys(),
                test_data.values()
            )
            self.db.execute(insert_sql, insert_parameter)

        # Act
        for line_number, line in enumerate(test_dat_file, start=1):
            sut: com_prefc_med_sojourn_ope_mapper.ComPrefcMedSojournOpeMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_prefc_med_sojourn_ope_mapper.ComPrefcMedSojournOpeMapper, f'{line_number}行目:マッパークラスが期通りか'
            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_prefc_med_sojourn_ope_update.csv'))
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_data_list]
        primary_keys_cos_surgery_code = [{'cos_surgery_code': columns['cos_surgery_code']} for columns in expect_data_list]
        actual_data_list = []
        sp_field_select_sql = """\
        SELECT * FROM src05.com_prefc_med_sojourn_ope
        WHERE
            dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND
            cos_surgery_code = :cos_surgery_code
        """
        for param_dcf_dsf_inst_cd, param_cos_surgery_code in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_cos_surgery_code):
            sp_field_data = self.db.execute_select(
                sp_field_select_sql,
                {**param_dcf_dsf_inst_cd, **param_cos_surgery_code})
            assert len(sp_field_data) == 1, '1件取得できていること'
            actual_data_list.append(sp_field_data[0])

        # 期待値検査
        ignore_columns = ['regist_ymd', 'update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_data_list, expect_data_list, ignore_col_name=ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_data_list, expect_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in ignore_columns:
                    if expect_row[expect_col_name] is None:
                        assert actual_row[actual_col_name] is None, f'{line_number}行目:{actual_col_name}が、登録されていないこと'
                    else:
                        assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

    def test_physical_delete(self):
        """
        Cases:
            COM_都道府県医療機能情報(短期滞在手術)テーブルのレコードを1件物理削除する
        Arranges:
            - CSVデータを用意し、読み込む
            - 削除対象となるレコードを登録する
        Expects:
            - 登録内容が期待値と一致すること
        """

        # Arrange
        # 処理日設定
        self.batch_context.syor_date = datetime.strftime(datetime.now(), '%Y/%m/%d')
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_prefc_med_sojourn_ope_delete.csv'))
        # 一旦全データをDBから削除
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_prefc_med_sojourn_ope', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # テストデータをDBに登録
        # DBデータを読み込む
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_prefc_med_sojourn_ope_before_delete.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_prefc_med_sojourn_ope',
                test_data.keys(),
                test_data.values()
            )
            self.db.execute(insert_sql, insert_parameter)

        # Act
        for line_number, line in enumerate(test_dat_file, start=1):
            sut: com_prefc_med_sojourn_ope_mapper.ComPrefcMedSojournOpeMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_prefc_med_sojourn_ope_mapper.ComPrefcMedSojournOpeMapper, f'{line_number}行目:マッパークラスが期通りか'
            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_prefc_med_sojourn_ope_delete.csv'))
        actual_record_count = self.db.execute_select('SELECT COUNT(*) AS count_num FROM src05.com_prefc_med_sojourn_ope')[0]['count_num']
        assert actual_record_count == len(expect_data_list), 'DBのレコード件数が期待値の件数と一致すること'
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_data_list]
        primary_keys_cos_surgery_code = [{'cos_surgery_code': columns['cos_surgery_code']} for columns in expect_data_list]
        actual_data_list = []
        sp_field_select_sql = """\
        SELECT * FROM src05.com_prefc_med_sojourn_ope
        WHERE
            dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND
            cos_surgery_code = :cos_surgery_code
        """
        for param_dcf_dsf_inst_cd, param_cos_surgery_code in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_cos_surgery_code):
            sp_field_data = self.db.execute_select(
                sp_field_select_sql,
                {**param_dcf_dsf_inst_cd, **param_cos_surgery_code})
            assert len(sp_field_data) == 1, '1件取得できていること'
            actual_data_list.append(sp_field_data[0])

        # 期待値検査
        ignore_columns = ['regist_ymd', 'update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_data_list, expect_data_list, ignore_col_name=ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_data_list, expect_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in ignore_columns:
                    if expect_row[expect_col_name] is None:
                        assert actual_row[actual_col_name] is None, f'{line_number}行目:{actual_col_name}が、登録されていないこと'
                    else:
                        assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'
