from messagebus import NakMessage, MessageBus, Message, Event
from messageprocessorutil import UuidMessageProcessor
from zeromqmessagehandler import MessageDecoder

from .._EventManager import EventManager


class PublishProcessor(UuidMessageProcessor):

    def __init__(self, event_manager, event_name=None):
        # type: (EventManager, str) -> None
        super(PublishProcessor, self).__init__(event_name)
        self.event_manager = event_manager

    def parse_data(self, data):
        return MessageDecoder.parse_event(data)

    def call_business(self, event):
        # type: (Event) -> Message
        return self.event_manager.publish_sync_event(event)

    def format_response(self, message_bus, message, event, received_event, reply):
        # type: (MessageBus, Message, Event, Event, Message) -> None
        message_bus.reply_message(message, reply)

    def format_exception(self, message_bus, message, event, input_obj, exception):
        message_bus.reply_message(message, NakMessage(data=str(exception).encode("utf-8")))

    def format_parse_exception(self, message_bus, message, event, data, exception):
        message_bus.reply_message(message, NakMessage(data=str(exception).encode("utf-8")))
