import typing

from api_library.date_time_actions.date_functions import system_arrow
from api_validations.validations_request import (
    InsertAccountRecord,
    UpdateAccountRecord,
    ListOptions,
)

from api_validations.core_response import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from databases import (
    AccountRecords,
    BuildIbans,
)
from databases.sql_models.building.build import Build
from databases.sql_models.others.enums import ApiEnumDropdown


class AccountRecordsListEventMethods(MethodToEvent):

    event_type = "SELECT"
    __event_keys__ = {
        "7192c2aa-5352-4e36-98b3-dafb7d036a3d": "account_records_list",
    }

    @classmethod
    def account_records_list(
        cls,
        list_options: ListOptions,
        token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
    ):
        if isinstance(token_dict, OccupantTokenObject):
            AccountRecords.pre_query = AccountRecords.filter_all(
                AccountRecords.company_id
                == token_dict.selected_occupant.responsible_company_id,
            )
        elif isinstance(token_dict, EmployeeTokenObject):
            AccountRecords.pre_query = AccountRecords.filter_all(
                AccountRecords.company_id == token_dict.selected_company.company_id,
            )
        AccountRecords.filter_attr = list_options
        records = AccountRecords.filter_all()
        return AlchemyJsonResponse(
            completed=True, message="Update Build record", result=records
        )


class AccountRecordsCreateEventMethods(MethodToEvent):

    event_type = "CREATE"
    __event_keys__ = {
        "31f4f32f-0cd4-4995-8a6a-f9f56335848a": "account_records_create",
    }

    @classmethod
    def account_records_create(
        cls,
        data: InsertAccountRecord,
        token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
    ):
        data_dict = data.excluded_dump()
        if isinstance(token_dict, OccupantTokenObject):
            build_iban = BuildIbans.filter_one(
                BuildIbans.iban == data.iban,
                BuildIbans.build_id == token_dict.selected_occupant.build_id,
            ).data
            if not build_iban:
                BuildIbans.raise_http_exception(
                    status_code="HTTP_404_NOT_FOUND",
                    error_case="UNAUTHORIZED",
                    message=f"{data.iban} is not found in company related to your organization",
                    data={
                        "iban": data.iban,
                    },
                )
            account_record = AccountRecords.find_or_create(**data.excluded_dump())
            return AlchemyJsonResponse(
                completed=True,
                message="Update Build record",
                result=account_record.get_dict(),
            )
        elif isinstance(token_dict, EmployeeTokenObject):
            # Build.pre_query = Build.select_action(
            #     employee_id=token_dict.selected_employee.employee_id,
            # )
            # build_ids_list = Build.filter_all(
            # )
            # build_iban = BuildIbans.filter_one(
            #     BuildIbans.iban == data.iban,
            #     BuildIbans.build_id.in_([build.id for build in build_ids_list.data]),
            # ).data
            # if not build_iban:
            #     BuildIbans.raise_http_exception(
            #         status_code="HTTP_404_NOT_FOUND",
            #         error_case="UNAUTHORIZED",
            #         message=f"{data.iban} is not found in company related to your organization",
            #         data={
            #             "iban": data.iban,
            #         },
            #     )
            bank_date = system_arrow.get(data.bank_date)
            data_dict["bank_date_w"] = bank_date.weekday()
            data_dict["bank_date_m"] = bank_date.month
            data_dict["bank_date_d"] = bank_date.day
            data_dict["bank_date_y"] = bank_date.year

            if int(data.currency_value) < 0:
                debit_type = ApiEnumDropdown.filter_by_one(
                    system=True, enum_class="DebitTypes", key="DT-D"
                ).data
                data_dict["receive_debit"] = debit_type.id
                data_dict["receive_debit_uu_id"] = str(debit_type.uu_id)
            else:
                debit_type = ApiEnumDropdown.filter_by_one(
                    system=True, enum_class="DebitTypes", key="DT-R"
                ).data
                data_dict["receive_debit"] = debit_type.id
                data_dict["receive_debit_uu_id"] = str(debit_type.uu_id)

            account_record = AccountRecords.find_or_create(**data_dict)
            account_record.save()
            account_record.update(is_confirmed=True)
            account_record.save()
            return AlchemyJsonResponse(
                completed=True,
                message="Create Account record are successful",
                result=account_record.get_dict(),
            )


class AccountRecordsUpdateEventMethods(MethodToEvent):

    event_type = "UPDATE"
    __event_keys__ = {
        "ec98ef2c-bcd0-432d-a8f4-1822a56c33b2": "account_records_update",
    }

    @classmethod
    def build_area_update(
        cls,
        build_uu_id: str,
        data: UpdateAccountRecord,
        token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
    ):
        if isinstance(token_dict, OccupantTokenObject):
            pass
        elif isinstance(token_dict, EmployeeTokenObject):
            pass

        return AlchemyJsonResponse(
            completed=False,
            message="Update Build record",
            result=None,
        )


class AccountRecordsPatchEventMethods(MethodToEvent):

    event_type = "PATCH"
    __event_keys__ = {
        "34c38937-42a2-45f1-b2ef-a23978650aee": "account_records_patch",
    }

    @classmethod
    def build_area_patch(
        cls,
        build_uu_id: str,
        data,
        token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
    ):
        return AlchemyJsonResponse(
            completed=False,
            message="Patch Build record",
            result=None,
        )


AccountRecordsListEventMethod = AccountRecordsListEventMethods(
    action=ActionsSchema(endpoint="/account/records/list")
)
AccountRecordsCreateEventMethod = AccountRecordsCreateEventMethods(
    action=ActionsSchema(endpoint="/account/records/create")
)
AccountRecordsUpdateEventMethod = AccountRecordsUpdateEventMethods(
    action=ActionsSchema(endpoint="/account/records/update")
)
AccountRecordsPatchEventMethod = AccountRecordsPatchEventMethods(
    action=ActionsSchema(endpoint="/account/records/patch")
)
