from logging import Logger

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


class AddItemsInteractor(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: (AddItemsRequest) -> None

        pos_id = validate_api_key(request, self.config.api_key_mapping)
        self.logger.info("Adding items to order. 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)
        price_list = self.pos_repository.get_price_list(model)

        for item in request.items:
            self.logger.info("Adding item. Context: {}, LineNumber: {}, ProductCode: {}; Quantity: {}".format(
                item.context,
                item.line_number,
                item.product_code,
                item.quantity
            ))
            self.pos_repository.add_item_to_order(
                pos_id=pos_id,
                pos_ot=pos_ot,
                price_list=price_list,
                item=item
            )

        pos_ot.blkopnotify = False
        pos_ot.updateOrderProperties(pos_id)
