from logging import Logger

from model.error_type import PosValidationErrorsType
from interactor.route.order.reopen_shopping_cart.dto import ReopenShoppingCartRequest
from model.config import Config
from model.exception import ValidationError
from model.order_detail import OrderDetail
from model.repository import PosRepositoryModel
from model.services import OrderServiceModel
from validation_util import \
    check_if_order_is_totaled, \
    check_if_business_day_is_opened, \
    check_if_operator_is_logged, validate_api_key


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

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

    def execute(self, request):
        # type: (ReopenShoppingCartRequest) -> OrderDetail
        pos_id = validate_api_key(request, self.config.api_key_mapping)
        if not pos_id:
            raise ValidationError(PosValidationErrorsType.PosIdNotFound)

        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)
        check_if_order_is_totaled(self.pos_repository, model)

        pos_ot = self.pos_repository.get_pos_ot(model)
        order = self.pos_repository.reopen_shopping_cart(
            pos_id=pos_id,
            pos_ot=pos_ot
        )

        order_detail = self.order_service.convert_mw_order_to_order_detail(order)

        return order_detail
