from logging import Logger

from helper import json_serialize
from interactor.route.order.change_items_quantity.dto import ChangeItemsQuantityRequest
from model.config import Config
from model.error_type import PosValidationErrorsType
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, \
    check_if_order_is_in_progress, \
    validate_api_key


class ChangeItemsQuantityInteractor(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: (ChangeItemsQuantityRequest) -> None

        pos_id = validate_api_key(request, self.config.api_key_mapping)
        self.logger.info("Changing items quantity. PosId: {}; Items: {}"
                         .format(pos_id, json_serialize(request.items)))

        if not request.items:
            raise ValidationError(PosValidationErrorsType.SaleItemsInvalid)

        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)

        self.pos_repository.change_line_quantity(model, pos_ot, request.items)
