from typing import Optional

from event_manager_api.shared.token import (
    TK_EVT_SUBSCRIBE,
    TK_EVT_UNSUBSCRIBE,
)
from hyper_visor.processor import (
    FindServiceProcessor,
    HealthCheckProcessor,
    RegServiceProcessor,
    SubscribeProcessor,
    UnsubscribeProcessor,
)
from hyper_visor.service import (
    EventManager,
    ServiceLocator,
)
from messagebus import DefaultToken
from messagehandler import MessageHandlerBuilder
from messageprocessor import (
    DefaultMessageProcessorExecutorFactory,
    MessageProcessorMessageHandler,
)
from messageprocessorutil import LoggingProcessorCallback
from msgbus import MBContext
from service_locator_api.shared.token import (
    TK_CMP_REG_SERVICE,
    TK_HV_FIND_SERVICE,
)

from ._HyperVisorMessageHandler import HyperVisorMessageHandler


class HyperVisorMessageHandlerBuilder(MessageHandlerBuilder):

    def __init__(self, mb_context: MBContext):
        self.mb_context = mb_context

        self.event_manager: Optional[EventManager] = None
        self.service_locator: Optional[ServiceLocator] = None

    def build_singletons(self):
        self.service_locator = ServiceLocator()
        self.event_manager = EventManager(mb_context=self.mb_context)

    def build_message_handler(self, message, event):
        message_handler = MessageProcessorMessageHandler(
            event_processors=None,
            message_processors={
                TK_HV_FIND_SERVICE: FindServiceProcessor(service_locator=self.service_locator),
                TK_CMP_REG_SERVICE: RegServiceProcessor(service_locator=self.service_locator),
                TK_EVT_SUBSCRIBE: SubscribeProcessor(event_manager=self.event_manager),
                TK_EVT_UNSUBSCRIBE: UnsubscribeProcessor(event_manager=self.event_manager),
                DefaultToken.TK_SYS_HEALTH_CHECK: HealthCheckProcessor(),
            },
            executor_factory=DefaultMessageProcessorExecutorFactory(
                [
                    LoggingProcessorCallback(),
                ]
            ),
        )

        return HyperVisorMessageHandler(
            message_handler=message_handler,
            event_manager=self.event_manager,
        )

    def destroy_message_handler(self, message_handler):
        return

    def destroy_singletons(self):
        return
