/*
Solar Conquest
Copyright (C) 2006 Greg Beaman

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

void CalculateAIMove(CObject* obj)
{
	int type = obj->GetData()->type;
	int ai = obj->aiType;

	if (ai == AI_TYPE_NORMAL || ai == AI_TYPE_ASHLEY || ai == AI_TYPE_RODNEY)
	{
		if (type == OBJ_TYPE_REPAIRSHIP || type == OBJ_TYPE_REPAIRTURRET)
		{
			//If we're a repair ship, we do not want to target healed units
			if (obj->target)
			{
				if (obj->target->GetHealth() >= obj->target->GetData()->maxHealth)
					obj->target = NULL;
			}
		}
		else if (type == OBJ_TYPE_TURRET || type == OBJ_TYPE_IMMOBILE_TURRET)
		{
			if (obj->target)
			{
				if (Distance(obj->GetPosition(),obj->target->GetPosition()) > obj->GetData()->attackRange)
					obj->target = NULL;
			}
		}
		if (!obj->target)
		{
			if (type == OBJ_TYPE_REPAIRSHIP || type == OBJ_TYPE_REPAIRTURRET)
				obj->target = FindClosestWoundedAlly(obj);
			else if (type == OBJ_TYPE_TURRET || type == OBJ_TYPE_IMMOBILE_TURRET)
				obj->target = FindClosestEnemy(obj,true,obj->GetData()->attackRange);
			else
				obj->target = FindClosestEnemy(obj);
		}
	}
	else if (ai == AI_TYPE_FOLLOWER)
	{
		if (obj->parent)
		{
			obj->target = obj->parent->target;
			if (!obj->target)
				obj->SetState(OBJ_STATE_FOLLOWING);
		}
	}

	if (obj->target)
		obj->SetState(OBJ_STATE_ATTACKING);
	
	if (obj->turret)
		CalculateAIMove(obj->turret);
} 
