Scriptname _00E_LightSwitchMainScript extends ObjectReference  

Actor Property PlayerRef Auto

; The brightness of some lights starts glitching if enabled more than once in a row, so we have to track the light's enable status.
Int iLightStatus = -1 ; -1 - Unknown, 0 - disabled, 1 - enabled
Int iEnterCounter = 0

Event OnLoad()
	If iLightStatus < 0
		RegisterForSingleUpdate(0.1)
	EndIf
EndEvent

Event OnTriggerEnter(ObjectReference akActionRef)
	if akActionRef == PlayerRef
		TurnSwitchOn()
	EndIf
EndEvent

Event OnTriggerLeave(ObjectReference akActionRef)
	if akActioNRef == PlayerRef
		TurnSwitchOff()
	EndIf
EndEvent

Event OnUpdate()
	If iEnterCounter <= 0 && iLightStatus != 0
		EnableDisableLight(0)
	EndIf
EndEvent

Function TurnSwitchOn()
	If iEnterCounter < 0
		iEnterCounter = 0 ; Failsafe, can become negative on version update...
	EndIf		
	iEnterCounter += 1
	If iLightStatus != 1
		EnableDisableLight(1)
	EndIf
EndFunction

Function TurnSwitchOff()
	iEnterCounter -= 1
	If iEnterCounter <= 0
		iEnterCounter = 0 ; Failsafe, can become negative on version update...
		RegisterForSingleUpdate(0.1)
	EndIf
EndFunction

Function EnableDisableLight(Int iNewStatus)
	Int iOldStatus = (iLightStatus as Int)
	iLightStatus = iNewStatus

	ObjectReference lightRef = GetLinkedRef()
	
	If iOldStatus < 0
		If lightRef.IsEnabled()
			iOldStatus = 1
		Else
			iOldStatus = 0
		EndIf
	EndIf

	If iOldStatus != iNewStatus
		If iNewStatus > 0
			lightRef.Enable()
		Else
			lightRef.Disable()
		EndIf
	EndIf
EndFunction