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

from sndcs_client.Subscriber import Subscriber
from sndcs_client.Config import config

import threading
import gobject

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

class EventSubscriber(threading.Thread, Subscriber):

    def __init__(self, callbacks, namespace=None):
        """
        callbacks is a dictionary of event:event_handler
        """
        threading.Thread.__init__(self)
        Subscriber.__init__(self)

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

        self.callbacks = callbacks
        self.subscribeMatch("^%s_.*$" % (self.namespace))

    def run(self):
        print "Starting the Event Subscriber..."
        log.debug("Starting the Event Subscriber")
        self.listen()

    def abort(self):
        self.unsubscribe("^%s_.*$" % (self.namespace))
        super(EventSubscriber,self).abort()

    def event(self, event):
        log.debug("Got event: %s", event)
        if self.callbacks.has_key(event.subject):
            for callback in self.callbacks[event.subject]:
                if event.subject in [ self.namespace + "_heartbeat", self.namespace + "_pong" ]: # Probably better way to do this but we don't want to call idle_add on this because a long running GUI process will uneccessarily prevent the heartbeat from updating and will cause the client to think the server is down
                    callback(event)
                else:
                    gobject.idle_add(callback, event)

