Scriptname _00E_FortAdBalorLeverScript extends ObjectReference  

Actor Property BossMage Auto
Actor Property PlayerRef Auto
NorPortcullisSCRIPT Property Door01 Auto
NorPortcullisSCRIPT Property Door02 Auto
ObjectReference Property EnterTrigger Auto
ObjectReference Property LeaveTrigger Auto
Bool bDoorsUpdateLocked = False

Event OnLoad()
	SetDefaultState()
EndEvent

Event OnReset()
	SetDefaultState()
EndEvent

;This has to be handled as a function, since OnLoad and OnReset can fire in either order, and we can't handle competing animation calls.
Function SetDefaultState()
	bDoorsUpdateLocked = False
	PlayAnimation("FullPull")
EndFunction

Function LockDoorsUpdate()
	While bDoorsUpdateLocked
		Utility.Wait(0.1)
	EndWhile
	bDoorsUpdateLocked = True
EndFunction

Function UnlockDoorsUpdate()
	bDoorsUpdateLocked = False
EndFunction

Function OpenCloseDoors(Bool bOpen)

	If bOpen != Door01.isAlreadyOpen
		If bOpen
			PlayAnimationAndWait("FullPush", "FullPushedUp")
		Else
			PlayAnimationAndWait("FullPull", "FullPulledDown")
		EndIf
		Door01.Activate(self)
		Door02.Activate(self)
		; Give some time for the busy state to kick in. The doors' animations take 3-4 secs anyway.
		Utility.Wait(2.0)
		While Door02.GetState() == "busy" || Door01.GetState() == "busy"
			Utility.Wait(0.1)
		EndWhile
	EndIf

EndFunction	

Event OnActivate(ObjectReference triggerRef)
	If triggerRef == PlayerRef
		; If the boss is dead (and nothing else is trying to open/close the doors ATM), 
		; the player can open/close the doors by interacting with the lever at the throne
		If bDoorsUpdateLocked == False
			LockDoorsUpdate()
			If BossMage.IsDead()
				OpenCloseDoors((Door01.isAlreadyOpen == False)) ; Invert the current open state of the doors
			EndIf
			UnlockDoorsUpdate()
		EndIf

	ElseIf triggerRef == BossMage || triggerRef == EnterTrigger
		; Spring the trap, if the boss is alive
		; Close the doors when the boss enters combat or the player enters the "enter" trigger
		LockDoorsUpdate()
		If BossMage.IsDead() == False
			OpenCloseDoors(False)
		EndIf
		UnlockDoorsUpdate()

	ElseIf triggerRef == LeaveTrigger
		; Failsafe - open the doors if the player leaves or enters the "leave" trigger encasing the whole boss chamber
		LockDoorsUpdate()
		OpenCloseDoors(True)
		UnlockDoorsUpdate()

	EndIf
EndEvent