#include "GroupPathFinderManager.h"
#include "GroupPathFinder.h"

#include "MemoryManager/debugNew.h"

using namespace ground;
using namespace std;

GroupPathFinderManager* GroupPathFinderManager::instance = NULL;
GroupPathFinderManager::GroupPathFinderManager(void)
{
}

GroupPathFinderManager::~GroupPathFinderManager(void)
{
	removeAllGroups();
}

GroupPathFinderManager& GroupPathFinderManager::getInstance()
{
	if (instance == NULL){
		instance = new GroupPathFinderManager();
	}
	return *instance;
}

void GroupPathFinderManager::destroy()
{
	delete instance;
	instance = NULL;
}

void GroupPathFinderManager::addGroup(GroupPathFinder* group)
{
	groups[group] = group;
}

void GroupPathFinderManager::removeGroup(GroupPathFinder* group)
{
	map<void*,GroupPathFinder*>::iterator it = groups.find(group);
	if (it != groups.end()){
		groups.erase(it);
	}
}

bool GroupPathFinderManager::containGroup(GroupPathFinder * group)
{
	return groups.find(group) != groups.end();
}

void GroupPathFinderManager::removeAllGroups()
{
	// on doit obligatoirement utiliser une boucle while car le delete fait appel au destructeur
	// de group qui lui même fait appel à la methode removeGroup...
	while(!groups.empty()){
		map<void*,GroupPathFinder*>::iterator it = groups.begin();
		GroupPathFinder * group = it->second;
		delete group;
	}
}

void GroupPathFinderManager::update(){
	vector<GroupPathFinder*> deletable;
	for(map<void*,GroupPathFinder*>::iterator it = groups.begin(); it != groups.end(); ++it){
		// le groupe ne contient plus d'unité, c'est donc qu'elle sont toutes arrivée, on peut les supprimer
		if (it->second->getUnits().empty()){
			deletable.push_back(it->second);
			it = groups.erase(it);
		}else{
			it->second->computeMinUnitSpeed();
		}
		if (it == groups.end()){
			break;
		}
	}
	for (vector<GroupPathFinder*>::iterator it = deletable.begin(); it != deletable.end(); ++it){
		delete *it;
	}
}

