class ACTION_SetEnemy extends ScriptedAction;

enum EEnemyChanging
{
	ECH_Never,
	ECH_Always,
	ECH_IfOutOfRange,
};

enum EEnemySelection
{
	ESEL_First,
	ESEL_Closest,
};

var(Action) class<Pawn> EnemyClass;
var(Action) name EnemyTag;
var(Action) bool bOnlyVisible;
var(Action) float MaxDistance;
var(Action) bool bSetViewTarget; // auto-set target on enemy
var(Action) EEnemyChanging AllowChangingEnemies;
var(Action) EEnemySelection EnemySelection;

function bool InitActionFor(ScriptedController C)
{
	local Controller EC;
	local float BestDist, CurDist;
	
	if ( EnemyTag == 'Clear' ) {	
		C.Enemy = none;
		if (bSetViewTarget)
			C.ScriptedFocus = none;
	}
	else {
		if ( C.Enemy != none && (C.Enemy.bDeleteMe || C.Enemy.Health <= 0) )
			C.Enemy = none;
		
		if ( C.Enemy != none && (AllowChangingEnemies == ECH_Never 
			|| (AllowChangingEnemies == ECH_IfOutOfRange 
				&& ((bOnlyVisible && !C.CanSee(C.Enemy)) || vsize(C.Pawn.Location - C.Enemy.Location) > MaxDistance))) )
		{
			return false;
		}
		
		BestDist = Square(MaxDistance);
		for ( EC = C.Level.ControllerList; EC != none; EC = EC.nextController ) {
			if ( EC.Pawn != none && ClassIsChildOf(EC.Pawn.class, EnemyClass)
				&& !EC.Pawn.bPendingDelete && !EC.Pawn.bDeleteMe && EC.Pawn.Health > 0
				&& (EC.Pawn.Tag == EnemyTag || EnemyTag == '') )
			{
				if ( bOnlyVisible && !C.CanSee(EC.Pawn) )
					continue;
					
				CurDist = VSizeSquared(C.Pawn.Location - EC.Pawn.Location); 
				if ( CurDist < BestDist ) {
					C.Enemy = EC.Pawn;
					BestDist = CurDist;
					if ( EnemySelection == ESEL_First)
						break;				
				}
			}
		}
		if ( bSetViewTarget && C.Enemy != none )
			C.ScriptedFocus = C.Enemy;
	}

	return false;	
}


	

defaultproperties
{
     EnemyClass=Class'Old2k4.Monster'
     MaxDistance=500.000000
     ActionString="set enemy"
     bValidForTrigger=False
}
