from logging import Logger
from memorycache import CacheManager

from model import CacheKeys
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

from typing import (
    Any,
    Dict,
)


class GetProductsInteractor(object):
    def __init__(
        self,                   # type: GetProductsInteractor
        logger,                 # type: Logger
        config,                 # type: Config
        pos_repository,         # type: PosRepositoryModel
        status_cache,           # type: Dict[str, Any[Dict[str, CacheManager], CacheManager]]
    ):
        # type: (...) -> None

        self.logger = logger
        self.config = config
        self.pos_repository = pos_repository
        self.status_cache = status_cache

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

        pos_id = validate_api_key(request, self.config.api_key_mapping)
        try:
            cache_menu_products = self.pos_repository.get_menu_data(
                pos_id=pos_id,
                service_period=self.status_cache[CacheKeys.SERVICE_PERIOD_KEY][pos_id],
            )
        except MessageBusException:
            raise ExternalServiceErrors(ExternalServicesErrorsType.ServiceUnavailable)

        return bytearray(cache_menu_products)
