#include "stdafx.h"
#include "Background.h"

#include "CellWarsGameManager.h"
#include "Infrastructure\Camera.h"
#include "Util\MathUtil.h"

const float Background::FLABBY_FACTOR = 0.025f;
const float Background::FLABBY_BORDER_FACTOR = 0.025f;

Background::Background() : currentPhase(0)
{
	SetPosition(theCamera.GetPosition());
	SetColor(1,1,1,1);
	ClearSpriteInfo();
	SetSize(theCamera.GetWorldMaxVertex() - theCamera.GetWorldMinVertex());
	SetName("Background");
	SetSprite("Resources/Images/background.png");
	theWorld.Add(this, LayerEnum::Background);
}

Background::~Background()
{
}

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

}

void Background::Render()
{
	Actor::Render();
}

void Background::Update(float dt)
{
	Actor::Update(dt);
	
	currentPhase = (currentPhase + dt * getCurrentFrequencyFactor());
	if (currentPhase > 2 * MathUtil::Pi)
	{
		if (theCellWarsGame.isGameSuccess())
			currentPhase = 2 * MathUtil::Pi;
		else
			currentPhase -= 2 * MathUtil::Pi;
	}
	
	SetPosition(theCamera.GetPosition());
	Vector2 baseSize(theCamera.GetWorldMaxVertex() - theCamera.GetWorldMinVertex());
	baseSize *= (1 + FLABBY_FACTOR + FLABBY_BORDER_FACTOR);
	float currSizeFactor = FLABBY_FACTOR * getBell(currentPhase) * getSinus(currentPhase);
	SetSize(baseSize * (1 + currSizeFactor));
}

float Background::getBell(float x)
{
	x -= MathUtil::Pi;		//phaseShift
	return exp(-(x*x)/2);
}

float Background::getSinus(float x)
{
	return sin(2 * x);
}

float Background::getCurrentFrequencyFactor()
{
	static const float BASE_FREQUENCY = 80/60;
	static const float FINAL_FREQUENCY = 150/60;
	static const float INCREASE_PER_SEC = (FINAL_FREQUENCY - BASE_FREQUENCY) / theCellWarsGame.getTimeToSurvive();
	float currFreq = 2 * MathUtil::Pi * (BASE_FREQUENCY + INCREASE_PER_SEC * theCellWarsGame.getPlayTime());
	return currFreq; 
}