from logging import Logger

from model.error_type import PosValidationErrorsType
from interactor.route.order.create.dto import (
    OrderCreateRequest,
    OrderCreateResponse
)
from model.config import Config
from model.exception import ValidationError
from model.repository import PosRepositoryModel
from validation_util import check_business_period, validate_api_key


class OrderCreateInteractor(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: (OrderCreateRequest) -> OrderCreateResponse

        pos_id = validate_api_key(request, self.config.api_key_mapping)
        model = self.pos_repository.get_model(pos_id)
        pos_ot = self.pos_repository.get_pos_ot(model)
        check_business_period(self.pos_repository, pos_id, self.config, pos_ot)

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

        order_id = self.pos_repository.create_order(pos_id, pos_ot, request.price_list, request.sale_type)
        self.logger.info("OrderId: {}".format(order_id))

        return OrderCreateResponse(order_id=order_id)
