import itertools

from mbcontextmessagehandler import MbContextMessageBus
from messagebus import Event
from model.event_dispatch import EventDispatch
from model.services import EventDispatcherService

EVENT_XML_TEMPLATE = ''.join(map(str.strip,
                                 ('<Event subject="AUDITLOGGER" type="{event_type}">',
                                  '    <AuditLog rowId="{row_id}" period="{business_period}" encoded="{encoded:d}" orderId="{order_id}" createdAt="{created_at_gmt}" evtTime="{event_time}">',
                                  '          {event_data}',
                                  '    </AuditLog>',
                                  '</Event>')))


class EventDispatcher(EventDispatcherService):
    def __init__(self, message_bus):
        # type: (MbContextMessageBus) -> None
        self.message_bus = message_bus

    def dispatch_event(self, event_to_dispatch):
        # type: (EventDispatch) -> None

        params = dict(itertools.chain.from_iterable((
            event_to_dispatch.__dict__.iteritems(),
            event_to_dispatch.log_entry.__dict__.iteritems())
        ))
        formatted_xml = EVENT_XML_TEMPLATE.format(**params)

        self.message_bus.publish_event(Event("AUDITLOGGER", event_to_dispatch.log_entry.event_type, formatted_xml))
