ScriptName footprintsFootstepsScriptBiped Extends ActiveMagicEffect

footprintsRefCountScript Property footprintsQuest Auto

string Property boneLeft  Auto
string Property boneRight Auto

ImpactDataSet Property footprintsNPCWalkLImpactset Auto
ImpactDataSet Property footprintsNPCWalkRImpactset Auto

Spell Property parentSpell Auto

Actor selfRef

bool refCounted = False

Function Register()
	If ( !refCounted )
		If ( !footprintsQuest.IncrementRefCount() )
			;Debug.Trace( "footprintsFootstepsScriptBiped - NPC Footprints at max limit, aborting." )
			GoToState( "dead" )
			return
		EndIf
		refCounted = True
	EndIf
EndFunction

Function Unregister()
	If ( refCounted )
		refCounted = False
		footprintsQuest.DecrementRefCount()
	EndIf
EndFunction

Event OnEffectStart( Actor target, Actor caster )
	;Debug.StartScriptProfiling( "footprintsFootstepsScriptBiped" )
	If ( !boneLeft  || !boneRight  )
		Debug.Trace( "Either boneLeft or boneRight are empty on " + self + ". Aborting..." )
		GoToState( "dead" )
	EndIf
	
	selfRef = target
	If ( footprintsQuest && selfRef && RegisterForAnimationEvent( selfRef, "FootLeft" ) && RegisterForAnimationEvent( selfRef, "FootRight" )  )
		;Debug.Trace( "Biped Footsteps Effect applied to " + selfRef + ". Race: " + selfRef.GetRace() +" on (" + self +")" )
		GoToState( "alive" )
	Else
		;Debug.Trace( "Failed to register for event" )
		GoToState( "dead" )
	EndIf
EndEvent

State alive

	Event OnBeginState()
		If ( footprintsQuest )
			Register()
		EndIf
	EndEvent
	
	Event OnAnimationEvent( ObjectReference akSelfRef, string e )
		If ( !akSelfRef )
			return
		EndIf
		
		;Debug.Trace( "AnimEvent: " + e + " delivered by " + selfRef.GetRace() + "("+self+") " )
		If ( e == "FootLeft" )
			;Debug.Trace( "Foot Left" )
			akSelfRef.PlayImpactEffect( footprintsNPCWalkLImpactset, boneLeft, 0, 0, -1, 512 )
		ElseIf ( e == "FootRight" )
			;Debug.Trace( "Foot Right" )
			akSelfRef.PlayImpactEffect( footprintsNPCWalkRImpactset, boneRight, 0, 0, -1, 512 )
		EndIf
	EndEvent
	
	Event OnDying( Actor killer )
		;Debug.Trace( "footprintsFootstepsScriptBiped - OnDying event on " + selfRef )
		GoToState( "dead" )
	EndEvent
	
	Event OnEffectFinish( Actor akTarget, Actor akCaster )
		;Debug.Trace( "footprintsFootstepsScriptBiped - OnEffectFinish event on " + selfRef )
		;Unregister()
		GoToState( "dead" )
	EndEvent
	
	Event OnEndState()
		If ( footprintsQuest )
			Unregister()
		EndIf
	EndEvent

EndState

State dead
	Event OnBeginState()
		If ( selfRef && parentSpell )
			selfRef.RemoveSpell( parentSpell )
		EndIf
	EndEvent
EndState
