
#include "Renderer.h"
#include "RenderableEntity.h"

#include "DustParticle.h"
#include "ParticleEngine.h"
#include "ParticleManager.h"

#include "ModelMD2.h"

#include <stdlib.h>

#include "MemoryManager/DebugNew.h"


using namespace RenderSystem;

RenderableEntity::RenderableEntity()
{
	armyColor[0] = armyColor[1] = armyColor[2] = 1.0f;
	isVisible = false;
	this->modelInstance.model = NULL;
	this->dustGenerator = NULL;
	inFogOfWar = false;
}

RenderableEntity::~RenderableEntity()
{
	if(this->modelInstance.model!=NULL)
		this->modelInstance.model->releaseInstance(&this->modelInstance);
}


void RenderableEntity::setProperties(const std::string& unitType, const std::string& armee)
{
	Renderer::getInstance().setupModelInstance(modelInstance,unitType,armee);
	setArmy(armee);
	setAnimation(WAIT);
}

void RenderableEntity::setArmy(const std::string& army){
	if (army == "Bleu"){
		armyColor[0] = 0.0f;
		armyColor[1] = 0.0f;
		armyColor[2] = 1.0f;
	}else if (army == "Rouge"){
		armyColor[0] = 1.0f;
		armyColor[1] = 0.0f;
		armyColor[2] = 0.0f;
	}else if (army == "Neutre"){
		armyColor[0] = 1.0f;
		armyColor[1] = 1.0f;
		armyColor[2] = 0.0f;
	}else{
		armyColor[0] = 0.0f;//problème=>couleur noir
		armyColor[1] = 0.0f;
		armyColor[2] = 0.0f;
	}
}

void RenderableEntity::setAnimation(AnimationType nextAnimation, bool mounted){
	// tableau contenant le numero de l'animation pour chaque AnimationType
	// TODO : adapter ca en fonction des models...
	static const int animTable[] = {0,1,3,4,5,7,8,9,10};
	int animIndex = 0;
	if (mounted){
		switch(nextAnimation){
			case WALK:
				animIndex = 7;
				break;
			case FIGHT:
				animIndex = 8;
				break;
			case WAIT:
				animIndex = 9;
				break;
			case DEATH:
				animIndex = 10;
				break;
		}
	}else{
		switch(nextAnimation){
			case WALK:
				animIndex = 1;
				break;
			case FIGHT:
				animIndex = 3;
				break;
			case WAIT:
				animIndex = 4;
				break;
			case DEATH:
				animIndex = 5;
				break;
		}
	}
	modelInstance.animState.nextAnim = animIndex;
	modelInstance.animState.nextFrame = 0;
	int iteration = rand()%5;
	for (int i = 0; i< iteration; i++){
		modelInstance.updateInstance_aabbAndAnimState(MD2_FRAME_TIME);
	}
}

RenderableEntity::AnimationType RenderableEntity::getCurrentAnimation(){
	static const RenderableEntity::AnimationType animTable[] = {NO_ANIMATION,WALK,NO_ANIMATION,FIGHT,WAIT,DEATH,NO_ANIMATION,WALK,FIGHT,WAIT,DEATH};
	return animTable[modelInstance.animState.curAnim];
}

void RenderableEntity::allowDust(bool allow){
	if (dustGenerator != NULL && this->inFogOfWar){
		dustGenerator->allowDust(allow);
	}
}

void RenderableEntity::setFogOfWarVisibility(bool info) {
	this->inFogOfWar = info;
}

bool RenderableEntity::isFogOfWarVisible() {
	return this->inFogOfWar;
}



