from logging import Logger

from interactor.route.payment.cancel.dto import (
    CancelPaymentRequest,
    CancelPaymentResponse
)
from model.config import Config
from model.repository import PosRepositoryModel
from validation_util import (
    check_if_business_day_is_opened,
    check_if_operator_is_logged,
    check_if_order_is_totaled,
    validate_api_key
)


class CancelPaymentInteractor(object):
    def __init__(
            self,
            logger,          # type: Logger
            config,          # type: Config
            pos_repository   # type: PosRepositoryModel
     ):
        # type: (...) -> None

        self.logger = logger
        self.config = config
        self.pos_repository = pos_repository

    def execute(
            self,
            request   # type: CancelPaymentRequest
    ):
        # type: (...) -> CancelPaymentResponse

        pos_id = validate_api_key(
            request=request,
            secure_api_key_list=self.config.api_key_mapping
        )

        model = self.pos_repository.get_model(pos_id)

        check_if_business_day_is_opened(
            repository=self.pos_repository,
            model=model
        )
        check_if_operator_is_logged(
            repository=self.pos_repository,
            model=model
        )
        check_if_order_is_totaled(
            repository=self.pos_repository,
            model=model
        )

        response = self.pos_repository.do_clear_tender(
            pos_id=pos_id,
            model=model,
            tender_id=request.tender_id
        )

        return CancelPaymentResponse(response)
