class ActionTargetInDistancePrereq extends IScriptablePrereq
{
	var m_targetRecord : weak< AIActionTarget_Record >;
	var m_distance : Float;
	var m_distanceStat : gamedataStatType;
	default m_distanceStat = gamedataStatType.Invalid;
	var m_invert : Bool;

	protected export override function Initialize( recordID : TweakDBID )
	{
		var prereqRecord : ActionTargetInDistancePrereq_Record;
		var statRecord : Stat_Record;
		prereqRecord = TweakDBInterface.GetActionTargetInDistancePrereqRecord( recordID );
		statRecord = TDB.GetStatRecord( TDB.GetForeignKey( recordID + T".distanceStat" ) );
		m_targetRecord = prereqRecord.Target();
		m_distance = prereqRecord.Distance();
		if( statRecord )
		{
			m_distanceStat = statRecord.StatType();
		}
		m_invert = prereqRecord.Invert();
	}

	protected const override function OnApplied( state : PrereqState, game : GameInstance, context : IScriptable )
	{
		state.OnChanged( IsFulfilled( game, context ) );
	}

	public export const override function IsFulfilled( game : GameInstance, context : IScriptable ) : Bool
	{
		var targetObject : weak< GameObject >;
		var owner : weak< ScriptedPuppet >;
		var ownerContext : ScriptExecutionContext;
		var maxDistance : Float;
		var distSqr : Float;
		var succ : Bool;
		var player : GameObject;
		var statsSystem : StatsSystem;
		owner = ( ( weak< weak< ScriptedPuppet > > )( context ) );
		if( !( AIHumanComponent.GetScriptContext( owner, ownerContext ) ) )
		{
			return ( ( m_invert ) ? ( true ) : ( false ) );
		}
		if( !( AIActionTarget.GetObject( ownerContext, m_targetRecord, targetObject ) ) )
		{
			return ( ( m_invert ) ? ( true ) : ( false ) );
		}
		if( m_distanceStat != gamedataStatType.Invalid )
		{
			statsSystem = GameInstance.GetStatsSystem( owner.GetGame() );
			player = GameInstance.GetPlayerSystem( owner.GetGame() ).GetLocalPlayerControlledGameObject();
			maxDistance = statsSystem.GetStatValue( player.GetEntityID(), m_distanceStat );
		}
		else
		{
			maxDistance = m_distance;
		}
		if( maxDistance < 0.0 )
		{
			return ( ( m_invert ) ? ( true ) : ( false ) );
		}
		distSqr = Vector4.DistanceSquared( owner.GetWorldPosition(), targetObject.GetWorldPosition() );
		succ = distSqr < ( maxDistance * maxDistance );
		return ( ( m_invert ) ? ( !( succ ) ) : ( succ ) );
	}

}

