import logging
import time
from multiprocessing import Process

import zmq

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


class ForwarderDevice(object):
    def __init__(self, pub_address, sub_address):
        # type: (str, str) -> None
        self.sub_address = pub_address
        self.push_address = sub_address
        self.process = Process(target=self.execute)

    def start(self):
        self.process.start()

    def stop(self):
        self.process.terminate()

    def execute(self):
        context = None
        frontend = None
        backend = None

        context = zmq.Context()
        try:
            # Socket facing clients
            frontend = context.socket(zmq.XSUB)
            frontend.bind(self.sub_address)
            # frontend.setsockopt(zmq.SUBSCRIBE, b"")

            # Socket facing services
            backend = context.socket(zmq.XPUB)
            backend.bind(self.push_address)

            zmq.device(zmq.FORWARDER, frontend, backend)
        except Exception as e:
            logger.exception("Could not start device.")
            print(e)
            print("bringing down zmq device")
        finally:
            if frontend is not None:
                frontend.close()
            if backend is not None:
                backend.close()

        context.destroy()
