#pragma warning (disable:4786)
#include "ai.hpp"
#include "ai move.hpp"
#include "globals.hpp"
#include <stack>
#include <utils\utils.h>

AIMove::AIMove (AI *parent)
{
	m_Parent = parent;
	while (!m_CurPath.empty ())
		m_CurPath.pop ();
}

AIMove::~AIMove (void)
{
}

bool AIMove::JoinFormation (AIFormation& formation)
{
	if (formation.AddMove (this))
	{
		m_InFormation = true;
		return true;
	}
	return false;
}

CommandEntry *AIMove::Think (double value,CommandEntry *lastcom)
{
	CommandEntry *com;
	if (newdes)
	{
		if (lastcom)
		{
			m_Parent->RemoveCommand (lastcom);
			delete lastcom;
		}

		if (!g_Map[curdes.x][curdes.y].passable)
			return NULL;

		newdes = false;

		if (!CalcPath (&m_CurPath,m_Parent->Location(),curdes,-1,true))
			return NULL;
	}
	if (m_CurPath.empty())
		return NULL;

	com = new CommandEntry ();

	memset (com,0,sizeof (CommandEntry));
	com->commandType = MOVE_CMD;

	PATHELEMENT temp = m_CurPath.top();
	m_CurPath.pop ();
	
//	com->commandData.moveData.dx = temp.x;
//	com->commandData.moveData.dy = temp.y;
	return com;
}

void AIMove::SetDestination (int x,int y)
{
	if ((x == m_Parent->Location().x) && (y == m_Parent->Location().y))
		return;
	curdes.x = x;
	curdes.y = y;
	newdes = true;
}

bool AIMove::SetFormationDes (int x,int y)
{
/*
	int i,min;
	int curx,cury;
	const int OFFSIZE = 8;
	float cost[OFFSIZE];
	int offset[OFFSIZE][2] = {
	{-1,-1},
	{-1,0},
	{-1,1},
	{0,-1},
	{0,1},
	{1,-1},
	{1,0},
	{1,1}
	};

	min = 0;
	curx = m_Parent->Location().x;
	cury = m_Parent->Location().y;
	if ((curx == x) && (cury == y))
		return true;
	for (i=0;i<OFFSIZE;i++)
	{
		if ((cost[i] = GetOneCost (curx,cury,curx+offset[i][0],cury+offset[i][1])) != -1)
			cost[i] += PathCostGuess (curx+offset[i][0],cury+offset[i][1],x,y);
		if (cost[min] == -1)
			min = i;
		else if ((cost[i] != -1) && (cost[i] < cost[min]))
			min = i;
	}
	if (cost[min] == -1)
		return false;

	while (!m_CurPath.empty())
		m_CurPath.pop();

	curx = m_Parent->Location().x;
	cury = m_Parent->Location().y;
	m_CurPath.push (PATHELEMENT (curx+offset[min][0],cury+offset[min][1]));
*/
	return true;
}
