from typing import Dict, Optional, List

from messagebus import MessageBus, Message, DefaultToken
from messageprocessor import MessageProcessorMessageHandler, MessageProcessor, MessageProcessorCallback, \
    DefaultMessageProcessorExecutorFactory
from simplehttprouter import Route

from ._HttpMessageProcessor import HttpMessageProcessor


class HttpMessageProcessorMessageHandler(MessageProcessorMessageHandler):
    def __init__(self, route_processor, subject_counter=None, callbacks=None):
        # type: (Dict[Route, MessageProcessor], Optional[Dict[str, int]], Optional[List[MessageProcessorCallback]]) -> None # noqa
        msg_dict = {
            DefaultToken.TK_HTTP_MSG: HttpMessageProcessor(route_processor)
        }
        executor_factory = None
        if callbacks is not None:
            executor_factory = DefaultMessageProcessorExecutorFactory(callbacks)
        super(HttpMessageProcessorMessageHandler, self).__init__(None,
                                                                 msg_dict,
                                                                 executor_factory,
                                                                 subject_counter)

    def handle_message(self, message_bus, message):
        # type: (MessageBus, Message) -> None
        if message.token == DefaultToken.TK_HTTP_MSG:
            message.data = message
        super(HttpMessageProcessorMessageHandler, self).handle_message(message_bus, message)
