#include "stdafx.h"
#include "Cell.h"

#include "CellWarsGameManager.h"

const float Cell::MAX_BASE_HP = 150;
const float Cell::STANDARD_OWN_MOVEMENT_SPEED = 3.0f;
const float Cell::STANDARD_DRIFT_AWAY_DISTANCE = 1.5f;
const int Cell::NUM_PARTS = 4;

Cell::Cell() : Damageable(MAX_BASE_HP), cellParts(new ParticleActor()), lastFrameLifePercentage(1)
{
	float xPos = MathUtil::RandomFloatInRange(theCamera.GetWorldMinVertex().X, theCamera.GetWorldMaxVertex().X);
	float yPos = MathUtil::RandomFloatInRange(theCamera.GetWorldMinVertex().Y, theCamera.GetWorldMaxVertex().Y);
	Vector2 spawnPos(xPos, yPos);

	SetPosition(spawnPos);
	SetColor(1,1,1,1);
	ClearSpriteInfo();
	SetSize(0);
	ChangeSizeTo(3, 3);
	SetName("Cell");
	SetSprite("Resources/Images/cell.png");
	theWorld.Add(this, LayerEnum::Cell);

	cellParts->SetPosition(this->GetPosition());
	cellParts->SetRotation(this->GetRotation());
	cellParts->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
	cellParts->SetEndColor(Color(1.0f, 1.0f, 1.0f, 0.0f));
	cellParts->SetSize(2);
	cellParts->SetSprite("Resources/Images/cellPart.png");
	cellParts->SetParticlesPerSecond(0);
	cellParts->SetMaxParticles(NUM_PARTS);
	//cellParts->SetEndScale();
	cellParts->SetParticleLifetime(3);
	cellParts->SetSpread(MathUtil::Pi);
	cellParts->SetSpeedRange(1.5f, 3.0f);
	//cellParts->SetAttractorStrength(2);
	cellParts->SetGravity(Vector2(0));
	theWorld.Add(cellParts);

	//std::cout << "Cell " << _name << std::endl;
}

Cell::~Cell()
{
	//std::cout << "~Cell " << _name << std::endl;
}

void Cell::PreDestroy()
{
	theCellWarsGame.addKilledCell();
	theCellWarsGame.removeCellFromGame(this);
	cellParts->Destroy();
}

void Cell::die()
{
	this->Destroy();
}

void Cell::ReceiveMessage(Message *m)
{
	Actor::ReceiveMessage(m);

}

void Cell::Render()
{
	Actor::Render();

}

void Cell::Update(float dt)
{
	Actor::Update(dt);
	driftAway(dt);

	
	float currLifePerc(getLifePercentage());
	float stageThreshold = 1;
	for (int i = 0; i < NUM_PARTS; ++i)
	{
		stageThreshold -= 1 / ((float)NUM_PARTS + 1);
		if (lastFrameLifePercentage >= stageThreshold &&
			currLifePerc < stageThreshold)
		{
			cellParts->SpawnAdditionalParticles(1);
		}
	}

	cellParts->SetPosition(this->GetPosition());
	//cellParts->SetAttractor(this->GetPosition());
	cellParts->SetRotation(MathUtil::RandomFloat() * MathUtil::Pi * 2);
	//updateHPString(this->GetPosition(), this->GetSize());

	lastFrameLifePercentage = getLifePercentage();
}

void Cell::driftAway(float dt)
{
	Cell* nearestCell = theCellWarsGame.getNearestCellFromActor(this);

	if (nearestCell)
	{
		Vector2 dist(GetPosition() - nearestCell->GetPosition());
		if (dist.Length() < STANDARD_DRIFT_AWAY_DISTANCE)
		{
			Vector2 velocity = Vector2::Normalize(dist);
			velocity *= STANDARD_OWN_MOVEMENT_SPEED;
			SetPosition(GetPosition() + velocity * dt);
		}
	}
}