#MUDPyE - (M)ulti-(U)ser (D)imension (Py)thon (E)ngine
#Copyright (C) 2005  Corey Staten

#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.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

#Send feedback/questions to MUDPyE@gmail.com

from mpmudobject import Ex

#Callbacks are in the form [timer, resetTimer, callbackID, argument]
#timer-Time left until callback activates.
#resetTimer-If greater than 0, timer will reset to this once callback is activated.
#funcName-Function to be called on target object.
#kwargs-Arguments to pass to function.

class CallbackHandler(object):
  def __init__(self, mudWorld):
    self.mudWorld = mudWorld
    self.callbackList = []

  def AddCallback(self, timer, resetTimer, objRef, funcName, kwargs):
    callback = [timer, resetTimer, objRef, funcName, kwargs]
    self.callbackList.append(callback)
    return callback

  def DelCallback(self, callback):
    try:
      self.callbackList.remove(callback)
    except IndexError:
      self.mudWorld.loggers["mud.scripterror"].warning("Attempt to delete non-existant callback.")

  def ProcessTime(self, units):
    self.callbackList.sort()
    working = True
    for callback in self.callbackList:
      callback[0] -= units
    execCallbacks = [callback for callback in self.callbackList if (callback[0] <= 0)]
    while len(execCallbacks) > 0:
      for callback in execCallbacks:
        #Kill invalid callbacks.
        if self.mudWorld.objDB.db.has_key(object.__getattribute__(callback[2], "objID")):
          Ex(callback[2], callback[3], **callback[4])
          if callback[1] > 0:
            callback[0] += callback[1]
          else:
            self.callbackList.remove(callback)
        else:
          self.callbackList.remove(callback)
      execCallbacks = [callback for callback in self.callbackList if (callback[0] <= 0)]