
#include "ArmyStupid.h"
#include "math.h"

#include "MemoryManager/debugNew.h"

using namespace ground;
using namespace std;

ArmyStupid::ArmyStupid(std::string& color) : Army(color)
{
	updateCounter = 0;
}

ArmyStupid::~ArmyStupid(void)
{
}

void ArmyStupid::updateAI()
{
	this->groundArmyInfo.update();

	updateCounter++;
	if (updateCounter < 10){
		printf("on groupe\n");
		// on regroupe les unitée
		for(vector<Unit*>::iterator it=this->units.begin(); it!=this->units.end();++it){
			if ((*it)->isWaiting())
			{
				// on suit l'allier le plus proche
				Unit* nearest = NULL;
				float dist = 9999.0f;
				for (vector<Unit*>::iterator jt=this->units.begin(); jt!=this->units.end();++jt){
					if (*it != *jt){
						float d = ((*it)->getPosition() - (*jt)->getPosition()).getLength();
						if (d < dist && d > 3){
							dist = d;
							nearest = *jt;
						}
					}
				}
				if (nearest != NULL){
					(*it)->follow(nearest,false);
				}
			}
		}
	}else{
		printf("on attaque\n");
		for(vector<Unit*>::iterator it=this->units.begin(); it!=this->units.end();++it){
			if (!(*it)->isInCombatPosture()){
				// on attaque l'ennemi le plus proche
				Unit* nearest = NULL;
				float dist = 9999.0f;
				for (vector<Unit*>::iterator jt=this->ennemyArmy->getUnits().begin(); jt!=this->ennemyArmy->getUnits().end();++jt){
					if ((*jt)->isAlive()){
						float d = ((*it)->getPosition() - (*jt)->getPosition()).getLength();
						if (d < dist){
							dist = d;
							nearest = *jt;
						}
					}
				}
				if (nearest != NULL){
					EnnemyUnit *ennemy = new EnnemyUnit(nearest,EnnemyUnit::VISIBLE);
					(*it)->attack(*ennemy);
				}
			}
		}
	}
}

void ArmyStupid::updateUnit()
{
	this->groundArmyInfo.removeAllUnits();
	std::vector<Unit*>::iterator it;
	for(it=this->units.begin(); it!=this->units.end();++it){
		if( (*it)->isAlive() ) {
			this->groundArmyInfo.addUnit((*it));
		}
		(*it)->update();
	}
	this->groundArmyInfo.update();
}

void ArmyStupid::setEnnemyArmy(Army* ea)
{
	this->ennemyArmy = ea;
	for (vector<Unit*>::iterator it = ea->getUnits().begin(); it != ea->getUnits().end(); ++it){
		ennemies[*it] = new EnnemyUnit(*it,EnnemyUnit::VISIBLE);
	}
}