import zmq
import time
import logging

from zmq.eventloop.zmqstream import ZMQStream
from server import config
from .common import context

TOPIC_BROADCAST_SERVICES = b'services'
TOPIC_BROADCAST_MONITORS = b'monitors'


class CSender(object):
    def __init__(self, port):
        self._socket = None
        self._port = port
        self._url = 'tcp://*:{port}'.format(port=port)
        self._stream = None

    def setup(self):
        try:
            self._socket = context.socket(zmq.PUB)
            self._socket.sndhwm = 1100000
            self._socket.bind(self._url)

            self._stream = ZMQStream(self._socket)

            time.sleep(1)
        except Exception as e:
            logging.error("Can't bind sender socket on port {port}: {exception}".format(port=self._port, exception=e))

    def publish_with_topic(self, topic, msg):
        try:
            self._stream.send_multipart([topic, msg])
        except Exception as e:
            logging.error('Exception: {}'.format(e))

    def broadcast_services(self, msg):
        self.publish_with_topic(TOPIC_BROADCAST_SERVICES, msg)

    def broadcast_monitors(self, msg):
        self.publish_with_topic(TOPIC_BROADCAST_MONITORS, msg)


_sender = CSender(config.instance.get_push_port())


def setup():
    global _sender
    _sender.setup()
