#include	"StatePlay.h"

#include	"Common.h"
#include	"ppAliens.h"
#include	"ppPlayer.h"

// constructor
// create score and lives text.
CStatePlay::CStatePlay() : CGameState(EGS_Play)
{
	m_iScoreTxtID = agk::CreateText("SCORE: 0");
	agk::SetTextPosition(m_iScoreTxtID, 0, 0);
	agk::SetTextSize(m_iScoreTxtID, 20);
	agk::SetTextColorAlpha(m_iScoreTxtID, 0);
	agk::SetTextVisible(m_iScoreTxtID, 0);
	agk::FixTextToScreen(m_iScoreTxtID, 1);

	m_iLivesTxtID = agk::CreateText("LIVES: 3");
	agk::SetTextPosition(m_iLivesTxtID, 300, 0);
	agk::SetTextSize(m_iLivesTxtID, 20);
	agk::SetTextColorAlpha(m_iLivesTxtID, 0);
	agk::SetTextVisible(m_iLivesTxtID, 0);
	agk::FixTextToScreen(m_iLivesTxtID, 1);
}

// destructor
CStatePlay::~CStatePlay()
{
}

// Run is called in each frame for the processing of the 'play-game' loop.
// display and update text. update player and aliens. check if game over 
// then return next game-state (end-state).
EGameState CStatePlay::Run(float fFrameTime)
{
	// main game
	if (!agk::GetTextVisible(m_iScoreTxtID))
	{
		agk::SetTextVisible(m_iScoreTxtID, 1);
		agk::SetTextVisible(m_iLivesTxtID, 1);
	}

	// fade in on screen text
	UINT alpha = agk::GetTextColorAlpha(m_iScoreTxtID);

	if (alpha < 255)
	{
		agk::SetTextColorAlpha(m_iScoreTxtID, alpha + 2);
		agk::SetTextColorAlpha(m_iLivesTxtID, alpha + 2);
	}

	// update the player, aliens and text
	m_refPlayer->UpdatePlayer();
	m_refAliens->UpdateAliens();

	UpdateText();

	if (m_refPlayer->IsGameOver())
		return EGS_End;

	return m_eState;
}

// reset player, bullets and aliens for a new round
void CStatePlay::Reset()
{
	m_refPlayer->ResetPlayer(1);
	m_refPlayer->ResetBullets();
	m_refAliens->ResetAliens();
}

// Updated the text(score and lives). Called also at each frame.
// Have neither score nor lives altered, nothing is changed.
void CStatePlay::UpdateText()
{
	static int last_score = -1, last_lives = -1;

	int score = m_refPlayer->GetScore();
	int lives = m_refPlayer->GetLives();

	if (score != last_score)
	{
		std::string line("SCORE: ");
		line += agk::Str(score);

		agk::SetTextString(m_iScoreTxtID, line.c_str());
		last_score = score;
	}

	if (lives != last_lives)
	{
		std::string line("LIVES: ");
		line += agk::Str(lives);

		agk::SetTextString(m_iLivesTxtID, line.c_str());
		last_lives = lives;
	}
}
