Scriptname _00E_TriggerboxSayNotInCombatScript extends ObjectReference  

Actor Property __Config_ActorRef Auto
Topic Property __Config_TopicID Auto
Quest Property __Config_Quest Auto
Int Property __Config_QuestMinStage Auto
Int Property __Config_QuestMaxStage Auto
Actor Property PlayerRef Auto
Spell Property AbCanSayNotInCombat Auto
Faction Property CanSayFaction Auto

Bool bIsInsideTrigger
Bool bDone

Event OnTriggerEnter(ObjectReference akActionRef)
	If akActionRef == PlayerRef
		bIsInsideTrigger = True
		If __Config_ActorRef.IsGhost()
			If CheckQuest() && __Config_ActorRef.Is3DLoaded()
				If bDone == False
					DoSay()
				EndIf
			EndIf
		Else
			__Config_ActorRef.AddSpell(AbCanSayNotInCombat, False)
			RegisterForSingleUpdate(1.1) ; Slightly more than 1 sec passes between adding the ability and its magic effect being applied
		EndIf
	EndIf
EndEvent

Event OnTriggerLeave(ObjectReference akActionRef)
	If akActionRef == PlayerRef
		bIsInsideTrigger = False
		UnregisterForUpdate()
		ActorCleanup()
	EndIf
EndEvent

Event OnUpdate()
	If CheckQuest() && __Config_ActorRef.IsInFaction(CanSayFaction)
		If bIsInsideTrigger && (bDone == False)
			DoSay()
		EndIf
	Else
		If bIsInsideTrigger && (bDone == False)
			RegisterForSingleUpdate(1.0)
		EndIf
	EndIf
EndEvent

Function DoSay()
	bDone = True
	__Config_ActorRef.Say(__Config_TopicID)
	ActorCleanup()
	Disable()
EndFunction

Function ActorCleanup()
	__Config_ActorRef.RemoveSpell(AbCanSayNotInCombat)
	__Config_ActorRef.RemoveFromFaction(CanSayFaction)
EndFunction

Bool Function CheckQuest()
	If __Config_Quest
		Int questStage = __Config_Quest.GetStage()

		If questStage > __Config_QuestMaxStage
			; We are past the max stage of the quest, no point in saying anything anymore.
			bDone = True
			ActorCleanup()
			Disable()
			Return False
		EndIf

		If questStage < __Config_QuestMinStage
			Return False
		EndIf
	EndIf

	Return True
EndFunction