#  Copyright (C) 2004  Henning Jacobs <henning@srcco.de>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  $Id: broadcaster.py 82 2004-07-11 13:01:44Z henning $

__all__ = ['Register', 'UnRegister', 'Broadcast', 'CurrentSource', 'CurrentTitle', 'CurrentData']

import debug

listeners = {}
currentSources = []
currentTitles = []
currentData = []

def Register(listener, arguments=(), source=None, title=None):
    if not listeners.has_key((source, title)):
        listeners[(source, title)] = []
    listeners[(source, title)].append((listener, arguments))

def UnRegister(listener, arguments=(), source=None, title=None):
    try:
        lst = listeners[(source, title)] 
        del lst[lst.index((listener, arguments))]
    except:
        debug.echo("broadcaster.UnRegister(): failed to unregister listener")

lastbroadcast = None
def Broadcast(source, title, data={}, onceonly=0):
    "Broadcast an Event / Notification to all registered Listeners"
    global lastbroadcast
    if onceonly and lastbroadcast == (source, title, data):
        # We don't want to let this broadcast be repeated
        return
    debug.echo("broadcaster.Broadcast(): %s %s %s" % (source, title, str(data))) 

    currentSources.append(source)
    currentTitles.append(title)
    currentData.append(data)

    listenerList = listeners.get((source, title), [])[:]
    if source != None:
        listenerList += listeners.get((None, title), [])
    if title != None:
        listenerList += listeners.get((source, None), [])

    for listener, arguments in listenerList:
        listener(*arguments)

    currentSources.pop()
    currentTitles.pop()
    currentData.pop()
    lastbroadcast = (source, title, data)

def CurrentSource():
    return currentSource[-1]

def CurrentTitle():
    return currentTitles[-1]

def CurrentData():
    return currentData[-1]
