#include "stinc.h"

gzBase::gzBase()
{
	int id = BASE_START_ID;
	while (true)
	{
		bool inUse = false;
		for (unsigned int i = 0; i < gzBaseManager::m_objList.Count(); i++)
		{
			if (gzBaseManager::m_objList[i]->GetId() == id)
			{
				inUse = true;
				break;
			}
		}
		if (!inUse)
		{
			this->m_Id = id;
			break;
		}
		id++;
	}
	this->m_deletePending = false;
	this->m_childOwner = NULL;
	this->m_createTime = (GetTickCount() - SystemTime);
	gzBaseManager::m_objList.Add(this);
}
gzBase::~gzBase()
{
	for (unsigned int i = 0; i < gzBaseManager::m_objList.Count(); i++)
	{
		if (gzBaseManager::m_objList[i] == this)
		{
			gzBaseManager::m_objList.Delete(i);
			break;
		}
	}
}
void gzBase::SetDeletePending()
{
	if (!this->m_deletePending)
	{
		this->m_deletePending = true;
		gzBaseManager::m_deletePendingList.Add(this);
	}
}
int gzBase::GetId()
{
	return this->m_Id;
}
bool gzBase::IsDeletePending()
{
	return this->m_deletePending;
}
unsigned long gzBase::GetCreateTime()
{
	return this->m_createTime;
}
gzManagerEvent *gzBase::GetChildOwner()
{
	return this->m_childOwner;
}
void gzBase::SetChildOwner(gzManagerEvent *owner)
{
	if (this->m_childOwner == NULL && owner)
	{
		owner->ChildObjCreation(this);
		this->m_childOwner = owner;
	}
}

aVector<gzBase *> gzBaseManager::m_objList;
aVector<gzBase *> gzBaseManager::m_deletePendingList;
int gzBaseManager::m_nextId = BASE_START_ID;
void gzBaseManager::Level_Loaded()
{
	gzBaseManager::m_nextId = BASE_START_ID;
}
void gzBaseManager::Unload()
{
	// Process pending delete object first
	gzBaseManager::Think();

	// Cleanup procedures first
	for (unsigned int i = 0; i < gzBaseManager::m_objList.Count(); i++)
	{
		stConsole::Out("Deleting \"%s\". [ID: %d]\n",
			gzBaseManager::m_objList[i]->GetName(),
			gzBaseManager::m_objList[i]->GetId()
		);
		gzBaseManager::m_objList[i]->Delete();
	}

	// Delete from memory
	while (gzBaseManager::m_objList.Count() > 0)
		delete gzBaseManager::m_objList[0];
	gzBaseManager::m_objList.Clear();
}
void gzBaseManager::Think()
{
	while (gzBaseManager::m_deletePendingList.Count() > 0)
	{
		if (gzBaseManager::m_deletePendingList[0]->GetChildOwner())
			gzBaseManager::m_deletePendingList[0]->GetChildOwner()->ChildObjDeletion(gzBaseManager::m_deletePendingList[0]);
		gzBaseManager::m_deletePendingList[0]->Delete();
		delete gzBaseManager::m_deletePendingList[0];
		gzBaseManager::m_deletePendingList.Delete(0);
	}
}
