ScriptName _00E_FortAdBalorBossScript Extends Actor

Actor Property PlayerRef Auto
ObjectReference Property tport1 Auto
ObjectReference Property tport2 Auto
ObjectReference Property tport3 Auto
ObjectReference Property doorLever Auto
VisualEffect Property teleportEffect Auto
Bool bIsInCombat = False
Bool bIsDying = False
Bool bDoingTeleportRoutine = False

; Backward compatibility
Actor Property bossMage Auto
Bool bport1 = True
Bool bport2 = True
Bool bport3 = True

Event OnCombatStateChanged(Actor akTarget, int aeCombatState)
	If aeCombatState > 0
		bIsInCombat = True
		DoTeleportRoutine()
	Else
		bIsInCombat = False
	EndIf
EndEvent

Event OnDying(Actor akKiller)
	bIsDying = True
EndEvent

Function DoTeleportRoutine()
	If bDoingTeleportRoutine
		Return
	EndIf
	bDoingTeleportRoutine = True

	doorLever.Activate(self) ; Close the doors

	Float myBaseHealth = GetBaseActorValue("Health")
	Float myLastHealth = myBaseHealth ; GetActorValue("Health")
	Bool bAllowTeleport = True
	Bool bDoTeleport = False
	Int nTeleportsDone = 0

	While (Is3DLoaded() && IsDead() == False)
		Float myCurHealth = GetActorValue("Health")
		
		If myCurHealth < myLastHealth
 			; Do teleport (again) only after losing health
			bAllowTeleport = True
		EndIf

		bDoTeleport = False
		If bAllowTeleport && bIsDying == False
			If myCurHealth < (myBaseHealth * 0.75) && nTeleportsDone < 1
				bDoTeleport = True
			ElseIf myCurHealth < (myBaseHealth * 0.5) && nTeleportsDone < 2
				bDoTeleport = True
			ElseIf myCurHealth < (myBaseHealth * 0.25) && nTeleportsDone < 3
				bDoTeleport = True
			EndIf
		EndIf

		If bDoTeleport
			TeleportMeAround()
			bAllowTeleport = False
			nTeleportsDone += 1
			myLastHealth = GetActorValue("Health")
			Utility.Wait(2.0) ; Some cooldown time before teleporting again
		Else
			myLastHealth = myCurHealth
			Utility.Wait(0.1)
		EndIf
	EndWhile

	bDoingTeleportRoutine = False
EndFunction

Function TeleportMeAround()
	teleportEffect.Play(self, 2.0)
	Utility.Wait(2.0)

	; Move me to the furthest teleport
	Float dist1 = PlayerRef.GetDistance(tport1)
	Float dist2 = PlayerRef.GetDistance(tport2)
	Float dist3 = PlayerRef.GetDistance(tport3)

	ObjectReference myTport = tport3
	If (dist1 > dist2 && dist1 > dist3)
		myTport = tport1
	Elseif (dist2 > dist1 && dist2 > dist3)
		myTport = tport2
	EndIf

	Actor myTarget = GetCombatTarget()
	If IsDead() == False && bIsDying == False && bIsInCombat
		MoveTo(myTport, abMatchRotation = True)
		; Try to resume combat if the mage gets the idea to stop it. It's not a bulletproof solution though.
		If myTarget 
			StartCombat(myTarget)
		EndIf
	EndIf
EndFunction