from logging import Logger

from model.error_type import PosValidationErrorsType
from interactor.route.order.get_detail.dto import OrderGetDetailRequest
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 validate_api_key


class OrderGetDetailInteractor(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: (OrderGetDetailRequest) -> OrderDetail

        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)

        order = self.pos_repository.get_current_order(model)

        if not order and not request.order_id:
            raise ValidationError(PosValidationErrorsType.OrderNotFound)

        order_id = request.order_id if request.order_id else order.get('orderId')

        if not order_id:
            raise ValidationError(PosValidationErrorsType.ParamsNotFound)

        order = self.pos_repository.get_order_details(pos_id, order_id, pos_ot)
        if order:
            return self.order_service.convert_mw_order_to_order_detail(order)

        raise ValidationError(PosValidationErrorsType.InvalidOrderId)
