import zmq

import threading
import time
from messagebus import MessageBus
from logging import Logger


class SocketResource(object):
    def __init__(self, context, pub_address):
        self.pub_socket = context.socket(zmq.PUB)
        self.pub_socket.connect(pub_address)
        # on the first connect zeromq takes a few msecs to establish the internal pipes so we have to wait a while
        # before sending the first message
        time.sleep(0.100)

    def __del__(self):
        self.pub_socket.close()


class PublisherMessageBus(MessageBus):
    def __init__(self, context, pub_address, logger):
        # type: (zmq.Context, str, Logger) -> None
        self.context = context
        self.pub_address = pub_address
        self.local_storage = threading.local()
        self.logger = logger

    def publish_event(self, event):
        type_data = event.event_type.encode("utf-8") if event.event_type is not None else b""
        event_data = b"" if event.data is None else event.data
        data = event.subject.encode("utf-8") + b" " + type_data + b"\0" + event_data

        if hasattr(self.local_storage, "resource"):
            pub_socket = self.local_storage.resource.pub_socket
        else:
            resource = SocketResource(self.context, self.pub_address)
            self.local_storage.resource = resource
            pub_socket = resource.pub_socket

        pub_socket.send(data)

    def send_message(self, component, message):
        pass

    def subscribe(self, subject):
        pass

    def reply_message(self, message, reply_message):
        pass

    def reply_event(self, event, reply_message):
        pass
