import zmq
import zmq.devices


class QueueDevice(object):
    def __init__(self, context, router_address, dealer_address, min_port, max_port):
        self.context = context
        self.router_address = router_address
        self.dealer_address = dealer_address
        self.min_port = min_port
        self.max_port = max_port

        zmq.devices.Device.context_factory = self.get_context
        self.device = zmq.devices.ThreadDevice(zmq.QUEUE, zmq.ROUTER, zmq.DEALER)

    def start(self):
        port = None
        if self.router_address.startswith("tcp://") and self.router_address.find(":", 6) < 0:
            port = self.device.bind_in_to_random_port(self.router_address, self.min_port, self.max_port)
        else:
            self.device.bind_in(self.router_address)
        self.device.bind_out(self.dealer_address)

        self.device.start()

        return port

    def stop(self):
        pass

    def get_context(self):
        return self.context
