import logging

from hyper_visor.service import EventManager
from messagebus import (
    DefaultToken,
    Message,
)
from messagehandler import MessageHandler
from messageprocessor import MessageProcessorMessageHandler

logger = logging.getLogger(__name__)

class HyperVisorMessageHandler(MessageHandler):
    def __init__(
        self,
        message_handler: MessageProcessorMessageHandler,
        event_manager: EventManager,
    ):
        self.message_handler = message_handler
        self.event_manager = event_manager

    def handle_event(self, message_bus, event):
        logger.debug("Start publishing: %s", event.subject)
        reply = self.event_manager.publish(event)

        if not event.synchronous:
            logger.debug("Async event, no reply necessary")
            return

        if reply is None:
            logger.debug("No one handled the event, creating default reply")
            reply = Message(token=DefaultToken.TK_EVT_EVENT)
        else:
            logger.debug("Someone handled the event, replying token [0x%08X]", reply.token)

        message_bus.reply_event(
            event=event,
            reply_message=reply,
        )

    def handle_message(self, message_bus, message):
        self.message_handler.handle_message(message_bus, message)
