// High Score Handler.
// Worthless Bums 2013.


// Test function to print $PersistentStats[].
function printPS ()
{//echo("printPS()");
	for (%i = 0; %i < 10; %i++)
	{
		echo($PersistentStats[%i]);
	}
}

// Start game timer.
function startGameTimer ()
{//echo("startGameTimer()");
	$startGameTimer = getScriptTimer();
}
// Stop game timer.
function stopGameTimer ()
{//echo("stopGameTimer()");
	$stopGameTimer = getScriptTimer();
}
// Calculate game played time.
function getGamePlayedTime ()
{//echo("getGamePlayedTime()");
	$gamePlayedTime += $stopGameTimer - $startGameTimer;
	return $gamePlayedTime;
}
// Get current time string.
function getCurrentTimeString ()
{//echo("getCurrentTimeString()");
	%playTime = $gamePlayedTime / 1000;	// Get time played in seconds, not milliseconds.
	// Calculate days played.
	%totalDays = mFloor(%playTime / 86400);
	%playTime %= 86400;
	// Calculate hours played.
	%totalHours = mFloor(%playTime / 3600);
	%playTime %= 3600;
	// Calculate minutes played.
	%totalMinutes = mFloor(%playTime / 60);
	echo(%playTime / 60);
	%playTime %= 60;
	// Calculate seconds played.
	%totalSeconds = mFloor(%playTime);
	
	%timeString = %totalDays @ "d, " @ %totalHours @ "h, " @ %totalMinutes @ "m, " @ %totalSeconds @ "s";
	return %timeString;
}

// Rank persistent stats by score.
function rankPersistentStats ()
{//echo("rankPersistentStats()");
	%swap = true;
	while (%swap)
	{
		%swap = false;
		for (%i = 0; %i < 9; %i++)
		{
			%currentScore = getWord($PersistentStats[%i], 3);
			if ($PersistentStats[%i] $= "null")
			{
				%currentScore = -9999999999;
			}
			%nextScore = getWord($PersistentStats[%i + 1], 3);
			if ($PersistentStats[%i + 1] $= "null")
			{
				%nextScore = -9999999999;
			}
			if (%currentScore < %nextScore)
			{
				%bufferString = $PersistentStats[%i + 1];
				$PersistentStats[%i + 1] = $PersistentStats[%i];
				$PersistentStats[%i] = %bufferString;
				%swap = true;
			}
		}
	}
}

// Inserts the specified persistent stats record if possible.
function insertPersistentStatsRecord (%currentRecord)
{//echo("insertPersistentStatsRecord()");
//echo("%currentRecord =" SPC %currentRecord);
	%currentScore = mRound(getWord(%currentRecord, 3));
	
	// Rank persistent stats in the array.
	rankPersistentStats();
	
	for (%i = 0; %i < 10; %i++)
	{
		if (getWord($PersistentStats[%i], 0) !$= "null")
		{
			%score = mRound(getWord($PersistentStats[%i], 3));
			//echo("%score =" SPC %score);
			//echo("%currentScore =" SPC %currentScore);
			if (%currentScore > %score	||
				getWord($PersistentStats[%i], 3) $= "")
			{
				// Shift records down.
				for (%j = 9; %j > %i; %j--)
				{
					$PersistentStats[%j] = $PersistentStats[%j - 1];
				}
				// Insert current record.
				$PersistentStats[%i] = %currentRecord;
				// Rank stats.
				//rankPersistentStats();
				
				return;
			}
		}
		else
		{
			$PersistentStats[%i] = %currentRecord;
			break;
		}
	}
	
	// Re-rank persistent stats in the array.
	//rankPersistentStats();
}

// Calculate the current score.
function calculateCurrentScore ()
{//echo("calculateCurrentScore()");
	%score = 0;
	
	// Score bonuses.
	if ($NewGamePlus < 0)	// $NewGamePlus sanity check!
	{
		$NewGamePlus = 0;
	}
	%scoreBonus += $NewGamePlus * 1000;		// 1000 points per New Game Plus!
	%scoreBonus += $GlobalStats.totalLevelsPassed * 100;
	%scoreBonus += $GlobalStats.totalPrimaryMissionObjectivesCompleted * 50;
	%scoreBonus += $GlobalStats.totalSecondaryMissionObjectivesCompleted * 25;
	%scoreBonus += $GlobalStats.totalKills * 10;
	%scoreBonus += $GlobalStats.totalMeleeAttacks * 2;
	%scoreBonus += $GlobalStats.totalDamageDealt * 1;
	%scoreBonus += $GlobalStats.totalWallsSmashed * 1;
	%scoreBonus += $GlobalStats.totalCratesSmashed * 1;
	%scoreBonus += $GlobalStats.totalDispensersUsed * 1;
	%scoreBonus += $GlobalStats.totalConsolesUsed * 1;
	%scoreBonus += $GlobalStats.totalItemsGrabbed * 1;
	%scoreBonus += $GlobalStats.totalChestsOpened * 1;
	%scoreBonus += $GlobalStats.totalLightSwitchesUsed * 1;
	%scoreBonus += $GlobalStats.totalItemsGrabbed * 1;
	// Score penalties.
	%scorePenalty -= $GlobalStats.currentTurn * 5;
	%scorePenalty -= $GlobalStats.totalSquadMemberDeaths * 200;
	%scorePenalty -= $GlobalStats.totalSurvivorsRecruited * 100;
	%scorePenalty -= $GlobalStats.totalAmmunitionExpended * 1;
	%scorePenalty -= $GlobalStats.totalDamageTaken * 10;
	%scorePenalty -= $GlobalStats.totalGuardModes * 10;
	
	// Score overall modifiers.
	switch ($difficultyLevel)
	{
		case 0:	// Easy.
			%scoreBonus = %scoreBonus * 0.75;
			%scorePenalty = %scorePenalty * 0.75;
			
		case 1:	// Normal.
			// Nothing!
			
		case 2:	// Hard.
			%scoreBonus = %scoreBonus * 1.25;
			%scorePenalty = %scorePenalty * 1.25;
			
		case 3:	// Brutal.
			%scoreBonus = %scoreBonus * 2.50;
			%scorePenalty = %scorePenalty * 2.50;
	}
	
	// Round the score.
	%score = mRound(%scoreBonus + %scorePenalty);
	
	// Return the score.
	return %score;
}
// Calculate the run modified score.
function calculateRunScore ()
{//echo("calculateRunScore()");
	%score = calculateCurrentScore();
	//%score -= $NewGamePlus * 1000;
	%score -= $GlobalStats.totalLevelsPassed * 300;
}

// Initializes high score data and GUI.
function initializeHighScore ()
{//echo("initializeHighScore()");
	// Load persistent stats from file.
	loadPersistentStats();
	// Rank persistent stats once loaded into the array.
	rankPersistentStats();
	
	// Use the description GuiMLTextCtrl to set the high score table.
	// NOTE: Probably going to need more colors.
	//$PersistentStats[10];
	/*
		0) Name of last marine
		1) Class of last marine
		2) Rank of last marine
		3) Score
		4) Deck
		5) Level
		6) Turns
		7) Cause of squad death (i.e. monster, knocked into space, new game)
		8) Deaths
	*/
	%labelsString = "      Last Marine   Deck (Level)       Last Threat   Score    Turn  Diff/Ver"	NL
					"---------------------------------------------------------------------------------";
	%numberString = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10";
	%nameString = "";
	%deckString = "";
	%threatString = "";
	%scoreString = "";
	%turnString = "";
	%deathsString = "";
	for (%i = 0; %i < 10; %i++)
	{
		// Class color.
		// NOTE: Colors seem to be only for [0, 5] but code says we should have [0, 9] so what gives?
		%classColor = "";
		/*switch$ (getWord($PersistentStats[%i], 1))
		{
			case "Leader":		%classColor = "\c0";
			case "Scout":		%classColor = "\c0";
			case "Grenadier":	%classColor = "\c0";
			case "Support":		%classColor = "\c0";
			case "Engineer":	%classColor = "\c0";
		}*/
		// Deck color.
		%deckColor = "";
		/*switch$ (getWord($PersistentStats[%i], 4))
		{
			case "Command":		%deckColor = "\c0";
			case "Engineering":	%deckColor = "\c0";
			case "Medical":		%deckColor = "\c0";
			case "Armory":		%deckColor = "\c0";
			case "Bridge":		%deckColor = "\c0";
			case "Alien":		%deckColor = "\c0";
		}*/
		%threatColor = "";
		%scoreColor = "";
		%turnColor = "";
		%deathsColor = "";
		%newGamePlusString = "";
		%difficultyString = "";
		switch (getWord($PersistentStats[%i], 9))
		{
			case 0:	// Easy.
				%difficultyString = "E";
			case 1:	// Normal.
				%difficultyString = "N";
			case 2:	// Hard.
				%difficultyString = "H";
			case 3:	// Brutal.
				%difficultyString = "B";
		}
		if ($NewGamePlus > 0)
		{
			%newGamePlusString = "NG+" @ $NewGamePlus;
		}
		if ($PersistentStats[%i] !$= "null")
		{
			%nameString 	= 	%nameString 	@	%classColor 	@ 	getWord($PersistentStats[%i], 2) @ ". " @ getWord($PersistentStats[%i], 0) @ "\n";
			%deckString 	= 	%deckString 	@	%deckColor 		@	getWord($PersistentStats[%i], 4) @ " (" @ getWord($PersistentStats[%i], 5) @ ")" @ %newGamePlusString @ "\n";
			%threatString 	= 	%threatString 	@	%threatColor	@ 	getWord($PersistentStats[%i], 7) @ "\n";
			%scoreString 	= 	%scoreString 	@	%scoreColor		@	getWord($PersistentStats[%i], 3) @ "\n";
			%turnString 	= 	%turnString 	@	%turnColor		@	getWord($PersistentStats[%i], 6) @ "\n";
			//%deathsString 	= 	%deathsString 	@	%deathsColor	@	getWord($PersistentStats[%i], 8) @ "\n";
			//%deathsString 	= 	%deathsString 	@	%deathsColor	@	%difficultyString @ "/" @ $currentGameVersion @ "\n";
			%deathsString 	= 	%deathsString 	@	%deathsColor	@	%difficultyString @ "/" @ getWord($PersistentStats[%i], 10) @ "\n";
		}
		else
		{
			%nameString = %nameString @ "---" @ "\n";
		}
	}
	highScoreLabels.setText(%labelsString);
	highScoreLabels.position = "80 200";
	highScoreNumber.setText(%numberString);
	highScoreNumber.position = "80 232";
	highScoreName.setText(%nameString);
	highScoreName.position = "128 232";
	highScoreDeck.setText(%deckString);
	highScoreDeck.position = "250 232";
	highScoreThreat.setText(%threatString);
	highScoreThreat.position = "406 232";
	highScoreScore.setText(%scoreString);
	highScoreScore.position = "528 232";
	highScoreTurn.setText(%turnString);
	highScoreTurn.position = "608 232";
	highScoreDeaths.setText(%deathsString);
	highScoreDeaths.position = "659 232";
	
	// Set Online High Scores.
	if ($ShowOnlineScores)
	{
		%text = "\c5      Online High Scores (" @ $LastTimeCheckStamp @ ")";
		%recordLimit = $OnlineScoresList.getCount();
		if (%recordLimit > 3)
		{
			%recordLimit = 3;	// Cap at 3!
		}
		for (%i = 0; %i < %recordLimit; %i++)
		{
			%record = $OnlineScoresList.getObject(%i);
			%text = %text		NL
					"\c8Score "	@ %record.score						@ ", " @
					"\c2NG+"	@ %record.newGamePlus				@ ", " @
					"\c6Turns "	@ %record.currentTurn				@ ", " @
					"\c4Level "	@ %record.totalLevelsPassed + 1		@ ", " @
					"\c8"		@ getDifficultyLabel(%record.difficultyLevel);
		}
		OnlineHighScores.setText(%text);
	}
	else
	{
		OnlineHighScores.setText("");
	}
}
function pushHighScore ()
{//echo("pushHighScore()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	tcpGetLevelData();
	waitForServerHighScores();
}
function waitForServerHighScores ()
{//echo("waitForServerHighScores()");
	if ($gettingServerData)
	{
		schedule(50, 0, "waitForServerHighScores");
	}
	else
	{
		continuePushHighScore();
	}
}
function continuePushHighScore ()
{//echo("continuePushHighScore()");
	initializeHighScore();
	Canvas.pushDialog(highScoreGui);
}
function popHighScore ()
{//echo("popHighScore()");
	Canvas.popDialog(highScoreGui);
}