#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, objID, funcName, argument]
#timer-Time left until callback activates.
#resetTimer-If greater than 0, timer will reset to this once callback is activated.
#callbackID-If the callback may later be cancelled, this is needed to cancel it.  Suggest that non-cancellable callbacks use 0.
#objID-The target objects ID.
#funcName-Function to be called on target object.
#argument-Argument  to pass to function.

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

  def AddCallback(self, timer, resetTimer, callbackID, objRef, funcName, argument):
    self.callbackList.append([timer, resetTimer, callbackID, objRef, funcName, argument])

  def DelCallback(self, callbackID, objID):
    for callback in self.callbackList:
      if (callback[2] == callbackID) and (callback[3] == objID):
        self.callbackList.remove(callback)

  def ProcessUnits(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:
        #Invalid objects will die here.
        if self.mudWorld.objDB.db.has_key(objRef._ID):
          Ex(callbackObj, callback[4], callback[5])
          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)]