Scriptname RemovableTorchSconce01SCRIPT extends ObjectReference Hidden 

import debug

Light Property Torch01 Auto
{The Torch01 we look for in the players inventory}

Activator Property RemovableTorch01 Auto
{Base object for torch activator that gets placed}

Bool Property StartsEmpty Auto
{If this is TRUE the sconce will start empty.  Default = FALSE}

Bool Property TorchInSconce = TRUE Auto Hidden
{TRUE when there is a torch in the sonce, FALSE when there isn't.  Default = TRUE}

ObjectReference Property PlacedTorch Auto Hidden
{A way to refer to the torch after it's been placed at the sconce}

Sound Property ITMGenericUp Auto
Sound Property ITMGenericDown Auto

Event OnCellLoad()
	;Trace("DARYL - " + self + "Cell Loaded")
	If IsDisabled()
		;Remove the old torch (if we had one)
		_DisablePlacedTorch()
		;Trace("STEVE - " + self + "Sconce is starting disabled, going to Awaiting Activation.")
		GoToState("AwaitingActivation")

	ElseIf (StartsEmpty == False) || (PlacedTorch != None)
		;Trace("DARYL - " + self + "Should start with a torch in it")
		_EnablePlacedTorch()
		GoToState("HasTorch")

	Else 
		_DisablePlacedTorch()
		GoToState("NoTorch")
	EndIf
EndEvent

Function RemoveTorch()
	_DisablePlacedTorch()
	GoToState("NoTorch")
EndFunction
	
State HasTorch
	Event OnActivate(ObjectReference TriggerRef)
		GoToState("Busy")
		;;Trace("DARYL - " + self + "Player has activated this sconce in the HasTorch State")
		_DisablePlacedTorch()
		TriggerRef.AddItem(Torch01)
		ITMGenericUp.Play(self)
		GoToState("NoTorch")
	EndEvent
EndState

State NoTorch
	Event OnActivate(ObjectReference TriggerRef)
		;;Trace("DARYL - " + self + "Player has activated the sconce in the NoTorch State")
		If TriggerRef.GetItemCount(Torch01) > 0
			GoToState("Busy")
			TriggerRef.RemoveItem(Torch01)
			_EnablePlacedTorch()
			ITMGenericDown.Play(self)
			GoToState("HasTorch")
		EndIf
	EndEvent
EndState

State Busy
	;Do Nothing
EndState

State AwaitingActivation
	Event OnActivate(ObjectReference obj)
		Self.Enable()
		OnCellLoad()
	EndEvent
EndState

Function _EnablePlacedTorch()
	If PlacedTorch
		PlacedTorch.Enable()
	Else
		PlacedTorch = Self.PlaceAtMe(RemovableTorch01)
	EndIf

	; No EnableLinkChain here because light sources get glitchy if Enable()/Disable() is called for them and they are already enabled/disabled
	ObjectReference CurrentLink = GetLinkedRef()
	While CurrentLink
		If CurrentLink.IsDisabled()
			CurrentLink.Enable()
		EndIf
		CurrentLink = CurrentLink.GetLinkedRef()
	EndWhile
EndFunction

Function _DisablePlacedTorch()
	If PlacedTorch
		PlacedTorch.Disable()
		PlacedTorch.Delete()
		PlacedTorch = None
	EndIf

	; No DisableLinkChain here because light sources get glitchy if Enable()/Disable() is called for them and they are already enabled/disabled
	ObjectReference CurrentLink = GetLinkedRef()
	While CurrentLink
		If CurrentLink.IsDisabled() == False
			CurrentLink.Disable()
		EndIf
		CurrentLink = CurrentLink.GetLinkedRef()
	EndWhile
EndFunction