# -*- coding: utf-8 -*-

from logging import Logger

import sysactions
from msgbus import MBEasyContext

from devicemanager.interactor import GetUsedServiceInteractor
from devicemanager.model import (
    Configs,
    ListenedTokens,
)
from devicemanager.processor import GetUsedServiceProcessor
from devicemanager.util import CacheManager
from messagebus import (
    Event,
    Message,
    MessageBus,
)
from messagehandler import (
    MessageHandler,
    MessageHandlerBuilder,
)
from messageprocessor import (
    DefaultMessageProcessorExecutorFactory,
    MessageProcessorMessageHandler,
)
from messageprocessorutil import LoggingProcessorCallback
from typing import Any


class DeviceManagerMessageHandlerBuilder(MessageHandlerBuilder):

    def __init__(
        self,
        configs,            # type: Configs
        message_bus,        # type: MessageBus
        mb_context,         # type: MBEasyContext
        logger,             # type: Logger
        input_logger,       # type: InputLoggerService
        callback_logger,    # type: Logger
    ):
        # type: (...) -> None

        self.configs = configs
        self.message_bus = message_bus
        self.mb_context = mb_context
        self.logger = logger
        self.input_logger = input_logger
        self.callback_logger = callback_logger
        self.cache_manager = None
        sysactions.mbcontext = message_bus.mbcontext

    def build_singletons(
        self,
    ):
        # type: (...) -> None

        self.cache_manager = CacheManager(sector_config=self.configs.sector_config)

    def build_message_handler(
        self,
        message,    # type: Message
        event,      # type: Event
    ):
        # type: (...) -> MessageHandler

        get_used_service_interactor = GetUsedServiceInteractor(cache_manager=self.cache_manager)
        get_used_service_processor = GetUsedServiceProcessor(get_used_service_interactor=get_used_service_interactor)

        message_handler = MessageProcessorMessageHandler(
            event_processors=None,
            message_processors={
                ListenedTokens.TK_GET_USED_SERVICE.value: get_used_service_processor
            },
            executor_factory=DefaultMessageProcessorExecutorFactory(
                [
                    LoggingProcessorCallback(self.callback_logger)
                ]
            ),
        )

        return message_handler

    def destroy_singletons(
        self,
    ):
        # type: (...) -> None

        pass

    def destroy_message_handler(
        self,
        message_handler,    # type: Any
    ):
        # type: (...) -> None

        pass
