from pubsub import pub
from zeroconf import ServiceStateChange

from src.api.server_proxy import RenderServerProxy


class ServerProxyManager:

    server_proxys = {}

    @classmethod
    def subscribe_to_listener(cls):
        """
          Subscribes the private class method '__local_job_status_changed' to the 'status_change' pubsub message.
          This should be called once, typically during the initialization phase.
        """
        pub.subscribe(cls.__zeroconf_state_change, 'zeroconf_state_change')

    @classmethod
    def __zeroconf_state_change(cls, hostname, state_change):
        if state_change == ServiceStateChange.Added or state_change == ServiceStateChange.Updated:
            cls.get_proxy_for_hostname(hostname)
        else:
            cls.get_proxy_for_hostname(hostname).stop_background_update()
            cls.server_proxys.pop(hostname)

    @classmethod
    def get_proxy_for_hostname(cls, hostname):
        found_proxy = cls.server_proxys.get(hostname)
        if hostname and not found_proxy:
            new_proxy = RenderServerProxy(hostname)
            new_proxy.start_background_update()
            cls.server_proxys[hostname] = new_proxy
            found_proxy = new_proxy
        return found_proxy
