# emacs-mode: -*- python-*-
from Plasma import *
from PlasmaTypes import *
from PlasmaKITypes import *
from PlasmaVaultConstants import *
from PlasmaNetConstants import *
import xLocalization
import string
import time

GateStateOpen = 1
GateStateClosing = 2
GateStateClosed = 3
GateStateOpening = 4

actClickableObject = ptAttribActivator(1, 'Act: Clickable Object')
ObjectMsg = ptAttribString(2, 'Object String')

class FuncChk01Clickables(ptModifier):
    __module__ = __name__

    def __init__(self):
        ptModifier.__init__(self)
        self.id = 1570001
        self.version = 1
        self.AgeName = None
        self.GateCollider = None
        self.Gate = None
        self.StartTime = 0
        self.GateState = GateStateClosed
        self.ZHeight = 19.5
        self.ZClosedPos = 10
        self.ZOpenPos = self.ZClosedPos - self.ZHeight
        self.GateTimerInterval = .03
        self.GateOpenTimerId = 1
        self.GateCloseTimerId = 2
        self.GateMoveDuration = 5.0

    def OnFirstUpdate(self):
        self.AgeName = PtGetAgeName()
        
    def OnServerInitComplete(self):
        # Obtain the gate collision object
        self.GateCollider = PtFindSceneobject("GateCollider",self.AgeName)
        if self.GateCollider == None:
            print 'OnServerInitComplete - could not find GateCollider!'
        # Obtain the visible gate object
        self.Gate = PtFindSceneobject("Gate",self.AgeName)
        if self.Gate != None:
            # Turn off its physics, since we will be moving it
            self.Gate.physics.suppress(true)
        else:
            print 'OnServerInitComplete - could not find Gate!'


    def OnNotify(self, state, id, events):
        print 'OnNotfiy: id=',
        print id
        if (id == actClickableObject.id):
            # Check for the button press 
            if ObjectMsg.value == "GateButton" and self.Gate != None:
                # Close the gate, if it is open
                if self.GateState == GateStateOpen:
                    self.StartTime = time.clock()
                    self.GateState = GateStateClosing
                    # Enable the gate collider, to prevent access during the close
                    self.GateCollider.physics.suppress(false)
                    # Register a timer callback for closing the gate
                    PtAtTimeCallback(self.key,self.GateTimerInterval,self.GateCloseTimerId)
                # Open the gate, if it is closed
                elif self.GateState == GateStateClosed:
                    self.StartTime = time.clock()
                    self.GateState = GateStateOpening
                    # Register a timer callback for opening the gate
                    PtAtTimeCallback(self.key,self.GateTimerInterval,self.GateOpenTimerId)


    def OnTimer(self, id):
        if (id == self.GateOpenTimerId):
            currentTime = time.clock()
            # Calculate the Z position of the gate, based on the
            # duration since the button press
            zPos = self.ZClosedPos - ((currentTime - self.StartTime)/self.GateMoveDuration)*self.ZHeight
            oldPos = self.Gate.position()
            newPos = ptPoint3(oldPos.getX(),oldPos.getY(),zPos)
            # Warp the visible gate object to the new position
            self.Gate.physics.warp(newPos)
            if zPos <= self.ZOpenPos:
                self.GateState = GateStateOpen
                # Turn off the collider - the gate is now open
                self.GateCollider.physics.suppress(true)
            else:
                PtAtTimeCallback(self.key,self.GateTimerInterval,self.GateOpenTimerId)
        elif (id == self.GateCloseTimerId):
            currentTime = time.clock()
            # Calculate the Z position of the gate, based on the
            # duration since the button press
            zPos = self.ZOpenPos + ((currentTime - self.StartTime)/self.GateMoveDuration)*self.ZHeight
            oldPos = self.Gate.position()
            newPos = ptPoint3(oldPos.getX(),oldPos.getY(),zPos)
            # Warp the visible gate object to the new position
            self.Gate.physics.warp(newPos)
            if zPos >= self.ZClosedPos:
                self.GateState = GateStateClosed
            else:
                PtAtTimeCallback(self.key,self.GateTimerInterval,self.GateCloseTimerId)



glue_cl = None
glue_inst = None
glue_params = None
glue_paramKeys = None
try:
    x = glue_verbose
except NameError:
    glue_verbose = 0

def glue_getClass():
    global glue_cl
    if (glue_cl == None):
        try:
            cl = eval(glue_name)
            if issubclass(cl, ptModifier):
                glue_cl = cl
            elif glue_verbose:
                print ('Class %s is not derived from modifier' % cl.__name__)
        except NameError:
            if glue_verbose:
                try:
                    print ('Could not find class %s' % glue_name)
                except NameError:
                    print 'Filename/classname not set!'
    return glue_cl



def glue_getInst():
    global glue_inst
    if (type(glue_inst) == type(None)):
        cl = glue_getClass()
        if (cl != None):
            glue_inst = cl()
    return glue_inst



def glue_delInst():
    global glue_inst
    global glue_cl
    global glue_paramKeys
    global glue_params
    if (type(glue_inst) != type(None)):
        del glue_inst
    glue_cl = None
    glue_params = None
    glue_paramKeys = None



def glue_getVersion():
    inst = glue_getInst()
    ver = inst.version
    glue_delInst()
    return ver



def glue_findAndAddAttribs(obj, glue_params):
    if isinstance(obj, ptAttribute):
        if glue_params.has_key(obj.id):
            if glue_verbose:
                print 'WARNING: Duplicate attribute ids!'
                print ('%s has id %d which is already defined in %s' % (obj.name,
                 obj.id,
                 glue_params[obj.id].name))
        else:
            glue_params[obj.id] = obj
    elif (type(obj) == type([])):
        for o in obj:
            glue_findAndAddAttribs(o, glue_params)

    elif (type(obj) == type({})):
        for o in obj.values():
            glue_findAndAddAttribs(o, glue_params)

    elif (type(obj) == type(())):
        for o in obj:
            glue_findAndAddAttribs(o, glue_params)




def glue_getParamDict():
    global glue_paramKeys
    global glue_params
    if (type(glue_params) == type(None)):
        glue_params = {}
        gd = globals()
        for obj in gd.values():
            glue_findAndAddAttribs(obj, glue_params)

        glue_paramKeys = glue_params.keys()
        glue_paramKeys.sort()
        glue_paramKeys.reverse()
    return glue_params



def glue_getClassName():
    cl = glue_getClass()
    if (cl != None):
        return cl.__name__
    if glue_verbose:
        print ('Class not found in %s.py' % glue_name)
    return None



def glue_getBlockID():
    inst = glue_getInst()
    if (inst != None):
        return inst.id
    if glue_verbose:
        print ('Instance could not be created in %s.py' % glue_name)
    return None



def glue_getNumParams():
    pd = glue_getParamDict()
    if (pd != None):
        return len(pd)
    if glue_verbose:
        print ('No attributes found in %s.py' % glue_name)
    return 0



def glue_getParam(number):
    pd = glue_getParamDict()
    if (pd != None):
        if (type(glue_paramKeys) == type([])):
            if ((number >= 0) and (number < len(glue_paramKeys))):
                return pd[glue_paramKeys[number]].getdef()
            else:
                print ('glue_getParam: Error! %d out of range of attribute list' % number)
        else:
            pl = pd.values()
            if ((number >= 0) and (number < len(pl))):
                return pl[number].getdef()
            elif glue_verbose:
                print ('glue_getParam: Error! %d out of range of attribute list' % number)
    if glue_verbose:
        print 'GLUE: Attribute list error'
    return None



def glue_setParam(id, value):
    pd = glue_getParamDict()
    if (pd != None):
        if pd.has_key(id):
            try:
                pd[id].__setvalue__(value)
            except AttributeError:
                if isinstance(pd[id], ptAttributeList):
                    try:
                        if (type(pd[id].value) != type([])):
                            pd[id].value = []
                    except AttributeError:
                        pd[id].value = []
                    pd[id].value.append(value)
                else:
                    pd[id].value = value
        elif glue_verbose:
            print "setParam: can't find id=",
            print id
    else:
        print 'setParma: Something terribly has gone wrong. Head for the cover.'



def glue_isNamedAttribute(id):
    pd = glue_getParamDict()
    if (pd != None):
        try:
            if isinstance(pd[id], ptAttribNamedActivator):
                return 1
            if isinstance(pd[id], ptAttribNamedResponder):
                return 2
        except KeyError:
            if glue_verbose:
                print ('Could not find id=%d attribute' % id)
    return 0



def glue_isMultiModifier():
    inst = glue_getInst()
    if isinstance(inst, ptMultiModifier):
        return 1
    return 0



def glue_getVisInfo(number):
    pd = glue_getParamDict()
    if (pd != None):
        if (type(glue_paramKeys) == type([])):
            if ((number >= 0) and (number < len(glue_paramKeys))):
                return pd[glue_paramKeys[number]].getVisInfo()
            else:
                print ('glue_getVisInfo: Error! %d out of range of attribute list' % number)
        else:
            pl = pd.values()
            if ((number >= 0) and (number < len(pl))):
                return pl[number].getVisInfo()
            elif glue_verbose:
                print ('glue_getVisInfo: Error! %d out of range of attribute list' % number)
    if glue_verbose:
        print 'GLUE: Attribute list error'
    return None



# local variables:
# tab-width: 4
