#include "MW4Headers.hpp"
#include "Adept\AdeptHeaders.hpp"

#include "mw4.hpp"
#include "moverai.hpp"
#include "Adept\Interface.hpp"
#include "Adept\Application.hpp"
#include "Adept\player.hpp"
#include "torso.hpp"

#include "aimovedata.hpp"

using namespace MechWarrior4;
using namespace MW4AI;
#pragma warning (push)
#include <algorithm>
#pragma warning (pop)

CMoveObjectData::CMoveObjectData (MW4AI::CRailGraph *graph,MoverAI *owner) : CMoveData (graph,owner)
{
	m_TargetObject = NULL;
	m_MoveType = MOVE_OBJECT;
}

CMoveObjectData::~CMoveObjectData (void)
{
	m_TargetObject = NULL;
}

void CMoveObjectData::Save (MemoryStream *stream)
{
	if (m_TargetObject)
	{
		*stream << true;
		*stream << m_TargetObject->objectID;
	}
	else
		*stream << false;
	CMoveData::Save (stream);
}

void CMoveObjectData::Load (MemoryStream *stream)
{
	bool flag;
	ObjectID object_id;

	*stream >> flag;
	m_TargetObject = NULL;
	if (flag)
	{
		*stream >> object_id;
		m_TargetObject = Cast_Object (MWObject *,NameTable::GetInstance()->FindData(object_id));
	}
	CMoveData::Load (stream);
}

void CMoveObjectData::InsertObject (Entity *who)
{
	inherited::InsertObject (who);
	m_TargetObject = who;
}

void CMoveObjectData::StartExecuting (MoverAI *ai,Stuff::Time till)
{
	CommandEntry *com;
	CPathRequest *req;
	CRailPath *path;

	inherited::StartExecuting (ai,till);

	req = Request ();
	if (!req->Done ())
	{
		Executing (false);
		return;
	}
	path = req->NodePath ();
	ai->NewPath (req->DetachNodePath ());
	com = ai->CreateSetSpeedCommand (Speed ());
	Check_Pointer (com);
	ai->ExecuteCommand (com);
}
void CMoveObjectData::PathDone (MoverAI *ai,Stuff::Time till,bool failed)
{
	CommandEntry *com;

	inherited::PathDone (ai,till,failed);
	if (failed)
		return;
	Verify (ai->m_Vehicle);
	com = ai->CreateSetSpeedCommand (0.0f);
	Check_Pointer (com);
	ai->ExecuteCommand (com);
	Done (true);
}

void CMoveObjectData::CreateRequests (const Stuff::Point3D& start,int usageflags)
{
	Point3D loc,third,fred;

	inherited::CreateRequests (start,usageflags);
	Check_Object (m_TargetObject);
	loc = (Point3D) m_TargetObject->GetLocalToWorld ();
	ConvertPointToGrid (loc);
	m_PathRequest = g_PathManager->AddRequest (gos_GetElapsedTime (),m_Graph,start,loc,usageflags,m_AI,m_AI->AllowTenMeter ());
}
bool CMoveObjectData::operator== (const CMoveObjectData& p1)
{
	if (!inherited::operator== ((inherited)p1))
		return false;
	if (m_TargetObject->objectID == p1.m_TargetObject->objectID)
		return false;
	return true;
}

Stuff::Point3D CMoveObjectData::Location (int id)
{
	Point3D loc,third,fred;

	Check_Object (m_TargetObject);
	loc = (Point3D) m_TargetObject->GetLocalToWorld ();
	ConvertPointToGrid (loc);
	return loc;
}

int CMoveObjectData::LocationSize (void) const
{
	return 1;
}
