

#include "Army.h"
#include "Renderer.h"

#include "MemoryManager/debugNew.h"

using namespace ground;
using namespace RenderSystem;

Army::Army(std::string& color)
{
	this->color = color;
	this->units.clear();
}

Army::~Army(void)
{
	std::vector<Unit*>::iterator it;
	for(it=this->units.begin(); it!=this->units.end();++it){
		delete (*it);
	}
	this->units.clear();
}

void Army::addUnit(unitEnumeration::UnitType type, Point2D& pos, float angle){
	Unit* u;
	Point2D p(pos.getX(), pos.getY());
	//TODO bien gérer le type et la couleur
	switch(type) {
		case unitEnumeration::ARCHER :
			u = new Archer();
			u->setProperties("Archer",color);
			break;

		case unitEnumeration::INFANTRY :
			u = new Infantry();
			u->setProperties("Infantry",color);
			break;

		case unitEnumeration::LANCER :
			u = new Lancer();
			u->setProperties("Lancer",color);
			break;
	}
	if(p.getX()<0) p.setX(0);
	if(p.getY()<0) p.setY(0);
	if(p.getX()>= GroundMap::getInstance().getWidth() ) p.setX(GroundMap::getInstance().getWidth()-1);
	if(p.getY()>= GroundMap::getInstance().getHeight() ) p.setY(GroundMap::getInstance().getHeight()-1);

	u->setPosition(p);
	u->setOrientation(angle);
	groundArmyInfo.addUnit(u);
	RenderSystem::Renderer::getInstance().addRenderableEntity(*u);
	this->units.push_back(u);
}

void Army::createUnits(unitEnumeration::UnitType type, int number, Point2D& pos, float radius){
	Point2D p;
	float alpha;
	float rad;
	for(int i=0;i<number;i++){
		do {
			alpha = rand();
			rad = radius*cos((float)rand());
			p.setCoord(pos.getX()+ rad*cos(alpha) ,pos.getY()+ rad*sin(alpha));
		}while(	GroundMap::getInstance().getCase((int)(p.getX()+0.5f),(int)(p.getY()+0.5f))==NULL ||				//dans le terrain
				!GroundMap::getInstance().getCase((int)(p.getX()+0.5f),(int)(p.getY()+0.5f))->isPassable());		//passable
		this->addUnit(type,p);
	}
}

void Army::mapChanged()
{
	std::vector<Unit*>::iterator it;
	for(it=this->units.begin(); it!=this->units.end();++it){
		delete (*it);
	}
	this->units.clear();
	groundArmyInfo.removeAllDangerGenerator();
	groundArmyInfo.removeAllUnits();
	groundArmyInfo.setupMapInfo(GroundMap::getInstance().getWidth(),GroundMap::getInstance().getHeight());
}


std::vector<Unit*>& Army::getUnits()
{
	return this->units;
}

ground::GroundArmyInfo& Army::getGroundArmyInfo()
{
	return this->groundArmyInfo;
}

void Army::createUnits(unitEnumeration::UnitType type, Point2D& orig, float width, float height, float angle,float offset)
{
	float halfWidth = width/2.0f;
	float halfHeight = height/2.0f;
	float alpha = angle*3.14f/180.0f;

	Point2D vw(cosf(alpha), sinf(alpha));
	Point2D vh(cosf(alpha+1.57f), sinf(alpha+1.57f));
	Point2D rOrig = orig - vw*halfWidth - vh*halfHeight;

	Point2D tmp;
	for(float i=0;i<width;i+=offset) {
		for(float j=0;j<height;j+=offset) {
			tmp = rOrig + vw*i + vh*j;
			if(GroundMap::getInstance().getCase(tmp.getX()+0.5f,tmp.getY()+0.5f)->isPassable())
				this->addUnit(type, tmp,angle);
		}
	}
}




