from logging import Logger

from interactor.route.order.close_shopping_cart.dto import CloseShoppingCartRequest
from model.config import Config
from model.order_detail import OrderDetail
from model.repository import PosRepositoryModel
from model.services import OrderServiceModel
from validation_util import check_if_business_day_is_opened, \
    check_if_operator_is_logged, check_if_order_is_in_progress, validate_api_key


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

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

    def execute(self, request):
        # type: (CloseShoppingCartRequest) -> OrderDetail

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

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

        order_detail = self.order_service.convert_mw_order_to_order_detail(order)

        return order_detail
