import logging
from threading import Thread

import zmq
from zmq import Context
from zmq.devices import ThreadDevice

logger = logging.getLogger("ZeroMqEventManager.ForwarderDevice")


class ForwarderDevice(object):
    def __init__(self, context, pub_address, sub_address):
        # type: (Context, str, str) -> None
        self.context = context
        self.sub_address = pub_address
        self.push_address = sub_address

        self.frontend = None
        self.backend = None

        self.running = False
        self.thread = Thread(target=self.execute)
        self.thread.daemon = True
        self.device = None

    def start(self):
        # Socket facing clients
        self.device = ThreadDevice(zmq.FORWARDER, zmq.XSUB, zmq.XPUB)
        self.device.daemon = True
        self.device.bind_in(self.sub_address)
        self.device.bind_out(self.push_address)
        self.device.start()

    def stop(self):
        pass

    def execute(self):
        while self.running:
            try:
                #ready = self.frontend.poll(1000, zmq.POLLIN)
                #if (ready & zmq.POLLIN) == 0:
                #    continue

                data = self.backend.recv()
                self.frontend.send(data)
                #zmq.device(zmq.FORWARDER, self.frontend, self.backend)
            except:
                logger.exception("Error processing message")
