from base64 import b64encode
from logging import getLogger

from messagebus import Event, MessageBus

from externals.events import PublishedEvents
from nperipherals_core.model.repository import NotificationRepository

logger = getLogger(__name__)


class MessageBusRepository(NotificationRepository):
    def __init__(self, message_bus):
        # type: (MessageBus) -> None

        self.message_bus = message_bus

    def notify(self, name, data):
        # type: (str, str) -> None

        subject = PublishedEvents.DEVICE_DATA.name
        payload = u'<Container><Device name="{}">{}</Device></Container>'.format(name, b64encode(data))

        logger.debug("Publishing [{}] with payload [{}]".format(subject, payload))

        self.message_bus.publish_event(Event(subject=subject, data=payload.encode("utf-8")))
