class AIJoinTargetsSquadTask extends AIbehaviortaskScript
{
	editable inlined var m_inCommand : AIArgumentMapping;

	protected override function Update( context : ScriptExecutionContext ) : AIbehaviorUpdateOutcome
	{
		var rawCommand : IScriptable;
		var typedCommand : AIJoinTargetsSquad;
		var target : weak< GameObject >;
		var squadName : CName;
		var ssi : SquadScriptInterface;
		var smc : SquadMemberBaseComponent;
		if( !( m_inCommand ) )
		{
			return AIbehaviorUpdateOutcome.FAILURE;
		}
		rawCommand = ScriptExecutionContext.GetScriptableMappingValue( context, m_inCommand );
		typedCommand = ( ( AIJoinTargetsSquad )( rawCommand ) );
		if( !( typedCommand ) )
		{
			return AIbehaviorUpdateOutcome.FAILURE;
		}
		if( !( GetGameObjectFromEntityReference( typedCommand.targetPuppetRef, ScriptExecutionContext.GetOwner( context ).GetGame(), target ) ) )
		{
			CancelCommand( context, typedCommand );
			return AIbehaviorUpdateOutcome.FAILURE;
		}
		smc = target.GetSquadMemberComponent();
		if( !( smc ) )
		{
			CancelCommand( context, typedCommand );
			return AIbehaviorUpdateOutcome.FAILURE;
		}
		squadName = smc.MySquadNameCurrentOrRecent( AISquadType.Combat );
		if( !( IsNameValid( squadName ) ) )
		{
			CancelCommand( context, typedCommand );
			return AIbehaviorUpdateOutcome.FAILURE;
		}
		ssi = smc.FindSquad( squadName );
		if( !( ssi ) )
		{
			CancelCommand( context, typedCommand );
			return AIbehaviorUpdateOutcome.FAILURE;
		}
		if( ssi.Join( ScriptExecutionContext.GetOwner( context ) ) )
		{
			return AIbehaviorUpdateOutcome.SUCCESS;
		}
		CancelCommand( context, typedCommand );
		return AIbehaviorUpdateOutcome.FAILURE;
	}

	protected final function CancelCommand( context : ScriptExecutionContext, typedCommand : AIJoinTargetsSquad )
	{
		if( typedCommand && typedCommand.state == AICommandState.Executing )
		{
			GetPuppet( context ).GetAIControllerComponent().StopExecutingCommand( typedCommand, false );
		}
		ScriptExecutionContext.SetMappingValue( context, m_inCommand, NULL );
	}

}

