# vim: ts=4 et sts=4 sw=4 autoindent

from Pyro.EventService.Clients import Subscriber as _Subscriber
import Pyro.core, Pyro.naming, Pyro.constants
from sndcs_common.PyroProxyMixin import PyroProxyMixin
from sndcs_client.Config import config

from sndcs_common.Logger import logger
log = logger.getLogger("Event Subscriber")

class Subscriber(_Subscriber, PyroProxyMixin):
    """ This class is just to override the __init__ of Pyro's Event Server
    Subscriber class so we can set the IP address that the daemon binds to """

    def __init__(self, ident=None, namespace=None):
        if namespace:
            self.namespace = namespace
        else:
            # Get the Pyro namespace from the config
            self.namespace = config.get("pyro", "namespace", "sndcs")

        # Let's get our IP address
        DCSServer = Pyro.core.getProxyForURI(self.formatPyronameString(self.namespace, ["DCSServer"]))
        address, port = DCSServer.clientIPAddress()

        log.info("DCS server sees us at address %s.", address)

        Pyro.core.CallbackObjBase.__init__(self)
        Pyro.core.initServer()
        Pyro.core.initClient()
        daemon = Pyro.core.Daemon(host=address) # This is really all we changed
        locator = Pyro.naming.NameServerLocator(identification=ident)
        self.NS = locator.getNS(host=Pyro.config.PYRO_NS_HOSTNAME)
        daemon.useNameServer(self.NS)
        daemon.connect(self)  #  will also set self.daemon...
        uri = self.NS.resolve(Pyro.constants.EVENTSERVER_NAME)
        self.eventservice=Pyro.core.getProxyForURI(uri)
        self.eventservice._setIdentification(ident)
        self.abortListen=0
        self.daemon=daemon  # make sure daemon doesn't get garbage collected now
