import logging

from messagebus import (
    LowLevelMessageBus,
    Message,
)
from messagehandler import (
    MessageHandlerBuilder,
)

logger = logging.getLogger(__name__)


class MessageHandlerExecutor(object):
    def __init__(
        self,                           # type: MessageHandlerExecutor
        message_bus,                    # type: LowLevelMessageBus
        message_handler_builder,        # type: MessageHandlerBuilder
    ):
        self.message_bus = message_bus
        self.message_handler_builder = message_handler_builder

        self.running = True

    def init(self):
        self.message_handler_builder.build_singletons()

    def end(self):
        self.message_handler_builder.destroy_singletons()

    def handle_message(
        self,           # type: MessageHandlerExecutor
        message,        # type: Message
    ):

        message_handler = None
        try:
            message_handler = self.message_handler_builder.build_message_handler(message=message)
            message_handler.handle_message(message_bus=self.message_bus, message=message)
        except (Exception,):
            logger.exception("Error handling message")
        finally:
            self.message_handler_builder.destroy_message_handler(message_handler=message_handler)

    def __enter__(self):
        self.init()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end()
