
function AISMN_MoveIntoAttackRange::OnEnter(%this, %data)
{
   %object = GetThisObject(%data);
   %team = %object.getTeam();
   
	// set a path to our target.
	%target = GetParameterTarget(%data);
	if (IsObject(%target) == false)
	{
	   return;
	}

   %position = %target.getPosition(); 
   %posX = getWord(%position, 0); 
   %posY = getWord(%position, 1);
   SetPathToSpot(%data, %posX, %posY);
   
   %object = GetThisObject(%data);
   %object.playThread(0, "run");
}

function AISMN_MoveIntoAttackRange::OnExit(%this,%obj)
{
	StopMoving(%obj);
   GetThisObject(%obj).playThread( 0, "root");
   return;
}

// EXIT 0: COMBAT CLEANUP- target is dead, target pursuit should stop
// EXIT 1: TARGET REACHED- start firing on the target
// EXIT 2: TARGET CHANGED- a new target is found, start pursuing
function AISMN_MoveIntoAttackRange::Update(%this, %data)
{
   %object = GetThisObject(%data);
   %team = %object.getTeam();
   
	// if the target is no longer alive, combat cleanup
	%target = GetParameterTarget(%data);
	if (IsObject(%target) == false || IsAlive(%target) == false)
	{
		ReturnValue(%data, 0);
		return;
	}

	// if unit is within attack range, start attacking
	if (IsWithinAttackRange(%data, %target) == true)
	{
		ReturnValue(%data, 1);
		return;
	}

	// if the object is being attacked by another object, stop
	// pursuing current target and head to next target
	%object = GetThisObject(%data);
	if (%data.isUnderAttack() == true &&
	   IsAttacking(%target, %object) == false)
	{
	   %attacker = %data.getAttackerOf();
	   SetParameterTarget(%data, %attacker);
	   ReturnValue(%data, 2);
	   return;
	}
	
	// if an ally is under attack, then attack this ally if it is
	// different from the target currently being pursued
	if (%data.allyIsUnderAttack() == true)
	{
	   %targetAI = slgQueryInterface(%target, $CID_AI);
	   %defender = %targetAI.getDefenderOf();
	   if (%defender == 0)
	   {
         %ally = %data.getAllyUnderAttack();
         %attacker = %data.GetAttackerOf(%ally);
         if (%attacker != 0)
         {
            SetParameterTarget(%data, %attacker);
            ReturnValue(%data, 2);
            return;
         }
	   }
	}
	//If the object is out of sight, return a different value
	else if (%object.getTeam() != $OST_PLAYER &&
	   %object.canSeeObj(%target) == false)
	{
      ReturnValue(%data, 0);
      return;
	}
	
	// the target moved, so recalculate the direction
	if (IsFollowingPath(%data) == false)
	{
      %position = %target.getPosition(); 
      %posX = getWord(%position, 0); 
      %posY = getWord(%position, 1);
      SetPathToSpot(%data, %posX, %posY);
	}
	
	ReturnValue(%data, -1);
}
