import threading

import zmq
from zmq import ContextTerminated

from flandre.nodes.Node import Node
from flandre.utils.Msg import KillMsg, TickMsg


class Broker(Node):
    def loop(self):
        def t():
            while True:
                msg = self.recv()
                if isinstance(msg, TickMsg):
                    pass
                elif isinstance(msg, KillMsg):
                    if msg.name == '':
                        self.context.term()
                        break

        threading.Thread(target=t, daemon=True).start()
        frontend = self.context.socket(zmq.XSUB)
        backend = self.context.socket(zmq.XPUB)
        frontend.bind(f"tcp://*:{self.fp}")
        backend.bind(f"tcp://*:{self.bp}")
        try:
            zmq.proxy(frontend, backend)
        except ContextTerminated as e:
            return
