# synarere -- a trivial Python IRC bot.
# Copyright (C) 2010 Michael Rodriguez.
# Rights to this code are documented in docs/LICENSE.

"""
This handles dispatching of commands parsed by regex, commands
added by modules, etc.
"""

# This is the IRC command hash table.
# This determines which functions are called
# when certain IRC events happen.
# This is initialised in irc.py.
irc = {}

# This is the IRC channel command hash table.
# This determines which functions are called
# when someone says certain things on IRC.
chan = {}

# This is the IRC channel addressed hash table.
# This determines which functions are called
# when someone addresses us on IRC.
chanme = {}

# This is the private message command hash table.
# This determines which functions are called
# when someone sends a certian PRIVMSG to the bot.
priv = {}

# This is the CTCP command hash table.
# This determines which functions are called
# when someone sends a certain CTCP.
ctcp = {}

def dispatch(hash, command, *args):
    """Dispatch commands."""

    if hash[command]['first']:
        hash[command]['first'](*args)

    for func in hash[command]['funcs']:
        func(*args)

    if hash[command]['last']:
        hash[command]['last'](*args)

def create(event, func, hash):
    """Add a function to an event's list of functions."""

    event = event.upper()

    try:
        test = hash[event]

    except KeyError:
        hash[event] = { 'first' : None,
                        'funcs' : [],
                        'last'  : None }

    if func in hash[event]['funcs']:
        return True

    else:
        hash[event]['funcs'].append(func)
        return True

def create_first(event, func, hash):
    """Add a function as an event's first function."""

    event = event.upper()

    try:
        test = hash[event]

    except KeyError:
        hash[event] = { 'first' : None,
                        'funcs' : [],
                        'last'  : None }

    if hash[event]['first']:
        return False

    else:
        hash[event]['first'] = func
        return True

def destroy(event, func, hash):
    """Remove a function from an event's list of functions."""

    event = event.upper()

    if func not in hash[event]['funcs']:
        return False

    else:
        hash[event]['funcs'].remove(func)
        return True

def destroy_first(event, func, hash):
    """Remove a function as an event's first function."""

    event = event.upper()

    hash[event]['first'] = None
