/**
* Path System
* @version: 01-29-2005
* @author Joseph 'Pcjoe' Florencio
*/

#include "fxsys.h"
#include "../studio_util.h"

// Constructor
CPathSystem::CPathSystem()
{	setFXEvent(NULL);
}

// Get Next ID
int CPathSystem::getNextID( void )
{	std::list<CPathManager>::iterator iterCurrent;

	// Search for valid ID
	int iID = 0;
	while(true)
	{	iID++;
		bool bIDUsed=false;
		ForEachIn(iterCurrent, m_Paths)
		{	if(iterCurrent->getID() == iID)
			{	bIDUsed = true;
			}
		}
		if(!bIDUsed)
			break;
	}
	return iID;
}


// Add Manager with ID
CPathManager *CPathSystem::addManager( int iID )
{	CPathManager pm(iID);
	pm.setFXEvent(getFXEvent());
	m_Paths.push_back(pm);
	std::list<CPathManager>::iterator iterLast = m_Paths.end();
	iterLast--;
	return (&(*iterLast));
}

CPathManager *CPathSystem::addManager( TiXmlElement *pElement )
{	CPathManager *pManager = addManager();
	pManager->readXML(pElement);
	return pManager;
}

// Add Manager
CPathManager *CPathSystem::addManager( void )
{	addManager(getNextID());
	std::list<CPathManager>::iterator iterLast = m_Paths.end();
	iterLast--;
	return (&(*iterLast));
}

//Get Manager by ID
CPathManager *CPathSystem::getManager( int id )
{	std::list<CPathManager>::iterator iterFind;
	ForEachIn(iterFind, m_Paths)
	{	if(iterFind->getID() == id)
		{	return (&(*iterFind));
		}
	}
	return NULL;
}

// Remove Manager
void CPathSystem::removeManager( int id )
{	std::list<CPathManager>::iterator iterRemove;
	ForEachIn(iterRemove, m_Paths)
	{	if(iterRemove->getID() == id)
		{	m_Paths.erase(iterRemove);
			return;
		}
	}
}

// Render Paths
void CPathSystem::RenderPaths( void )
{	// Set Texture
	if ( !gEngfuncs.pTriAPI->SpriteTexture( (struct model_s *)gEngfuncs.GetSpritePointer( LoadSprite("sprites/white.spr") ), 0 ))
	{	return;
	}
	// Render paths
	std::list<CPathManager>::iterator iterRender;
	ForEachIn(iterRender, m_Paths)
	{	iterRender->RenderPath();
	}
}

// Write XML
TiXmlElement *CPathSystem::writeXML( void )
{	TiXmlElement *pPaths = new TiXmlElement("paths");
	// Write data to XML
	std::list<CPathManager>::iterator iterRender;
	ForEachIn(iterRender, m_Paths)
	{	pPaths->LinkEndChild(iterRender->writeXML());
	}
	return pPaths;
}

// read XML
void CPathSystem::readXML( TiXmlElement *pElement )
{	if(!pElement)
	{	return;
	}

	// Find paths
	TiXmlElement *pPath=NULL;
	IterateXML(pPath,pElement)
	{	addManager(pPath);
	}
}