from logging import Logger

from model.error_type import PosValidationErrorsType
from interactor.route.order.cancel.dto import OrderCancelRequest
from model.config import Config
from model.exception import ValidationError
from model.repository import PosRepositoryModel
from validation_util import \
    check_if_business_day_is_opened, \
    check_if_operator_is_logged, \
    validate_api_key


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

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

    def execute(self, request):
        # type: (OrderCancelRequest) -> None

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

        model = self.pos_repository.get_model(pos_id)

        check_if_business_day_is_opened(self.pos_repository, model)
        check_if_operator_is_logged(self.pos_repository, model)

        if not self.pos_repository.has_current_order(model):
            raise ValidationError(PosValidationErrorsType.OrderNotFound)

        pos_ot = self.pos_repository.get_pos_ot(model)
        self.pos_repository.void_order(
            pos_id=pos_id,
            pos_ot=pos_ot,
            order_id=request.order_id,
        )
