from logging import Logger

from model.config import Config
from model.error_type import ExternalServicesErrorsType
from model.exception import ExternalServiceErrors
from model.repository import PosRepositoryModel
from interactor.route.menu.get_products.dto import GetProductsRequest
from validation_util import validate_api_key
from messagebus import MessageBusException


class GetProductsInteractor(object):
    def __init__(self, logger, config, pos_repository, cache_menu_products):
        # type: (Logger, Config, PosRepositoryModel, bytearray) -> None

        self.logger = logger
        self.config = config
        self.pos_repository = pos_repository
        self.cache_menu_products = cache_menu_products

    def execute(self, request):
        # type: (GetProductsRequest) -> bytearray

        validate_api_key(request, self.config.api_key_mapping)
        if not self.cache_menu_products:
            try:
                self.cache_menu_products = self.pos_repository.get_menu_data()
            except MessageBusException:
                raise ExternalServiceErrors(ExternalServicesErrorsType.ServiceUnavailable)

        if not self.cache_menu_products:
            raise ExternalServiceErrors(ExternalServicesErrorsType.MenuDataNotAvailable)

        return bytearray(self.cache_menu_products)
