from logging import Logger

from messagehandler import MessageHandlerBuilder
from messageprocessor import MessageProcessorMessageHandler, DefaultMessageProcessorExecutorFactory
from messageprocessorutil import LoggingProcessorCallback
from zeromqservicelocator import \
    ServiceLocator, \
    TK_SERVICE_LOCATOR_REGISTER_SERVICE, \
    TK_SERVICE_LOCATOR_LOOKUP_SERVICE, \
    TK_SERVICE_LOCATOR_KEEP_ALIVE
from zeromqservicelocator.processor import RegisterServiceProcessor, LocateServiceProcessor
from zeromqservicelocator.processor import KeepAliveProcessor


class ServiceLocatorMessageHandlerBuilder(MessageHandlerBuilder):
    def __init__(self, config, logger):
        # type: (dict, Logger) -> None
        self.config = config
        self.logger = logger

        self.service_locator = None  # type: ServiceLocator

    def build_singletons(self):
        self.service_locator = ServiceLocator()

    def build_message_handler(self, message, event):
        handled_tokens = {
            TK_SERVICE_LOCATOR_REGISTER_SERVICE: RegisterServiceProcessor(self.service_locator),
            TK_SERVICE_LOCATOR_LOOKUP_SERVICE: LocateServiceProcessor(self.service_locator),
            TK_SERVICE_LOCATOR_KEEP_ALIVE: KeepAliveProcessor(self.service_locator),
        }
        return MessageProcessorMessageHandler(
            None,
            handled_tokens,
            executor_factory=DefaultMessageProcessorExecutorFactory([LoggingProcessorCallback(self.logger)]))

    def destroy_message_handler(self, message_handler):
        pass

    def destroy_singletons(self):
        pass
