// Online form submission.
// Worthless Bums 2014


// GETs data from Steam Marines server.
function getData ()
{//echo("getData()");
	%httpObj = new HTTPObject();
	%url = "www.SteamMarines.com:80";
	%URI = "/onlineServer/scores/dailyScore_02-12-2014.txt";
	%query = "";
	%httpObj.get(%url, %URI, %query);
}
// Handle a line from the server.
// NOTE: This is the callback from invoking function getData()!
function HTTPObject::onLine (%this, %line)
{//echo("HTTPObject::onLine()");echo("Fetch at" SPC getScriptTimer());
	// Print the line to the console.
	echo(%line);
	// This should be a single record (this function gets invoked multiple times per multi-line file!
	$HighScoreList[$HighScoreListLength] = %line;
	$HighScoreListLength++;
}
function getHighScoreData ()
{//echo("getHighScoreData()");echo("Start fetch at" SPC getScriptTimer());
	// Declare high score variables.
	$HighScoreList[0] = "";
	$HighScoreListLength = 0;
	// Get data.
	if (!isObject($myHttpObject))
	{
		$myHttpObject = new HttpObject();
	}
    $myHttpObject.get("www.SteamMarines.com:80", "/onlineServer/scores/dailyScore_02-16-2014.dat", "");
	//$myHttpObject.get("www.WorthlessBums.com:80", "/steammarines/onlineServer/scores/dailyScore_02-16-2014.dat", "");
	// Wait some amount of time before pushing High Score data!
}
function toggleSendServerData ()
{//echo("toggleSendServerData()");
	$OptInDataSend = !$OptInDataSend;
	if ($OptInDataSend)
	{
		versionText.setText($currentGameVersion @ " - Sending data to server. Thank you!");
	}
	else
	{
		versionText.setText($currentGameVersion @ " - Not sending data to server.");
	}
}
function TimeCheck ()
{//echo("TimeCheck()");
    %obj = new TCPObject(TimeCheck);
	%obj.connect("nist1-ny2.ustiming.org:13");	// Server grabbed from list at: http://tf.nist.gov/tf-cgi/servers.cgi#
}
function TimeCheck::onLine (%this, %line)
{//echo("TimeCheck::onLine()");
	if (%line !$= "")
	{
		/*echo("Julian Date is: " 	@ getword(%line, 0));
		echo("The Date is: "		@ getword(%line, 1));
		echo("The Time in UTC is: " @ getword(%line, 2));
		if (getword(%line,3) $= "50")
		{
			echo("Time is Daylight Savings Time (DST)");
		}
		else
		{
			echo("Time is Standard Time (ST)");
		}*/
		$TimeCheckStamp = getword(%line, 1);
		$LastTimeCheckStamp = $TimeCheckStamp;
	}
}
function tcpGetLevelData ()
{//echo("tcpGetLevelData()");
	// Get time first!
	$TimeCheckStamp = "";
	TimeCheck();
	waitForTimeCheckGet();
}
function waitForTimeCheckGet ()
{//echo("waitForTimeCheckGet()");
	if ($TimeCheckStamp $= "")
	{
		schedule(50, 0, "waitForTimeCheckGet");
	}
	else
	{
		continueTcpGetLevelData();
	}
}
function continueTcpGetLevelData ()
{//echo("continueTcpGetLevelData()");
	$gettingServerData = true;
	$getServerLine = 0;
	%obj = new TCPObject(TCPObj);   
	%obj.connect("www.SteamMarines.com:80");
}
function tcpSendLevelData ()
{//echo("tcpSendLevelData()");
	// Get time first!
	$TimeCheckStamp = "";
	TimeCheck();
	waitForTimeCheck();
}
function waitForTimeCheck ()
{//echo("waitForTimeCheck()");
	if ($TimeCheckStamp $= "")
	{
		schedule(50, 0, "waitForTimeCheck");
	}
	else
	{
		continueTcpSendLevelData();
	}
}
function continueTcpSendLevelData ()
{//echo("continueTcpSendLevelData()");
	$sendingServerData = true;
	%obj = new TCPObject(TCPObj);   
	%obj.connect("www.SteamMarines.com:80");
}
function TCPObj::onConnected (%this)
{//echo("TCPObj::onConnected()");
	if ($sendingServerData)
	{//echo("sending data!");
		%data = "";
		%data = %data @ "difficultyLevel=" 				@ mRound($difficultyLevel)							@ "&";
		%data = %data @ "newGamePlus=" 					@ mRound($NewGamePlus)								@ "&";
		%data = %data @ "score=" 						@ mRound(calculateCurrentScore())					@ "&";
		%data = %data @ "currentTurn=" 					@ mRound($GlobalStats.currentTurn)					@ "&";
		%data = %data @ "totalLevelsPassed=" 			@ mRound($GlobalStats.totalLevelsPassed)			@ "&";
		%data = %data @ "totalSquadMemberDeaths=" 		@ mRound($GlobalStats.totalSquadMemberDeaths)		@ "&";
		%data = %data @ "totalSurvivorsRecruited=" 		@ mRound($GlobalStats.totalSurvivorsRecruited)		@ "&";
		%data = %data @ "totalKills=" 					@ mRound($GlobalStats.totalKills)					@ "&";
		%data = %data @ "totalAmmunitionExpended=" 		@ mRound($GlobalStats.totalAmmunitionExpended)		@ "&";
		%data = %data @ "totalMeleeAttacks=" 			@ mRound($GlobalStats.totalMeleeAttacks)			@ "&";
		%data = %data @ "totalDamageDealt="				@ mRound($GlobalStats.totalDamageDealt)				@ "&";
		%data = %data @ "totalDamageTaken=" 			@ mRound($GlobalStats.totalDamageTaken)				@ "&";
		%data = %data @ "totalEnemiesKnockedIntoSpace=" @ mRound($GlobalStats.totalEnemiesKnockedIntoSpace)	@ "&";
		%data = %data @ "totalWallsSmashed=" 			@ mRound($GlobalStats.totalWallsSmashed)			@ "&";
		%data = %data @ "totalCratesSmashed=" 			@ mRound($GlobalStats.totalCratesSmashed)			@ "&";
		%data = %data @ "totalDispensersUsed=" 			@ mRound($GlobalStats.totalDispensersUsed)			@ "&";
		%data = %data @ "totalConsolesUsed=" 			@ mRound($GlobalStats.totalConsolesUsed)			@ "&";
		%data = %data @ "totalDoorsOpened=" 			@ mRound($GlobalStats.totalDoorsOpened)				@ "&";
		%data = %data @ "totalDoorsClosed=" 			@ mRound($GlobalStats.totalDoorsClosed)				@ "&";
		%data = %data @ "totalItemsGrabbed=" 			@ mRound($GlobalStats.totalItemsGrabbed)			@ "&";
		%data = %data @ "totalItemsUsed=" 				@ mRound($GlobalStats.totalItemsUsed)				@ "&";
		%data = %data @ "totalChestsOpened=" 			@ mRound($GlobalStats.totalChestsOpened)			@ "&";
		%data = %data @ "totalLightSwitchesUsed=" 		@ mRound($GlobalStats.totalLightSwitchesUsed)		@ "&";
		%data = %data @ "totalGuardModes=" 				@ mRound($GlobalStats.totalGuardModes);
		%htmlpost = "POST /onlineServer/submitDailyScore.php HTTP/1.0\nHost: www.SteamMarines.com:80\nUser-Agent: Steam Marines " @ $currentGameVersion @ " \nAccept: */*\nContent-length: " @ strlen(%data) @ "\nContent-type: application/x-www-form-urlencoded\n\n" @ %data;
		%this.send(%htmlpost @ " \r\n");
	}
	else if ($gettingServerData)
	{//echo("getting data!");
		%data = "";
		%htmlpost = "POST /onlineServer/scores/dailyScore_" @ $TimeCheckStamp @ ".dat HTTP/1.0\nHost: www.SteamMarines.com:80\nUser-Agent: Steam Marines " @ $currentGameVersion @ " \nAccept: */*\nContent-length: " @ strlen(%data) @ "\nContent-type: application/x-www-form-urlencoded\n\n" @ %data;
		%this.send(%htmlpost @ " \r\n");
	}
}
function TCPObj::onDisconnect (%this)
{//echo("TCPObj::onDisconnect()");
	//%this.delete();	// Causing a fatal assert!
	%this.schedule(32, 0, "delete");
}
function TCPObj::onLine (%this, %line)
{//echo("TCPObj::onLine()");echo(%line);
	if ($sendingServerData)
	{//echo(%line);
		$sendingServerData = false;
	}
	else if ($gettingServerData)
	{//echo(%line);
		// We want the 15th line only!
		%taggedLine = 15;
		$getServerLine++;
		if ($getServerLine == %taggedLine)
		{//echo(%line);
			if (isObject($OnlineScoresList))
			{
				$OnlineScoresList.safeDelete();
			}
			// Grab data.
			$OnlineScoresList = new SimSet();
			%i = 0;
			%dataBlockLength = 24;
			%block = getWord(%line, 0);	// Not really %i at this point...
			// Track top 3 highest scores for the day!
			$DailyScoreFirstIndex = -1;
			$DailyScoreSecondIndex = -1;
			$DailyScoreThirdIndex = -1;
			%blockLimit = 999;	// Limit number of records to parse!
			while (%block !$= ""	&&
				   %i < %blockLimit)
			{//echo("Record " @ %i + 1 @ " Difficulty = " @ getDifficultyLabel(%block) @"\n         Score      = " @ getWord(%line, %i * %dataBlockLength + 2));
				%onlineRecord = new ScriptObject ()
				{
					difficultyLevel = 				getWord(%line, %i * %dataBlockLength);
					newGamePlus = 					getWord(%line, %i * %dataBlockLength + 1);
					score = 						getWord(%line, %i * %dataBlockLength + 2);
					currentTurn = 					getWord(%line, %i * %dataBlockLength + 3);
					totalLevelsPassed =				getWord(%line, %i * %dataBlockLength + 4);
					totalSquadMemberDeaths = 		getWord(%line, %i * %dataBlockLength + 5);
					totalSurvivorsRecruited = 		getWord(%line, %i * %dataBlockLength + 6);
					totalKills = 					getWord(%line, %i * %dataBlockLength + 7);
					totalAmmunitionExpended = 		getWord(%line, %i * %dataBlockLength + 8);
					totalMeleeAttacks = 			getWord(%line, %i * %dataBlockLength + 9);
					totalDamageDealt = 				getWord(%line, %i * %dataBlockLength + 10);
					totalDamageTaken = 				getWord(%line, %i * %dataBlockLength + 11);
					totalEnemiesKnockedIntoSpace = 	getWord(%line, %i * %dataBlockLength + 12);
					totalWallsSmashed = 			getWord(%line, %i * %dataBlockLength + 13);
					totalCratesSmashed = 			getWord(%line, %i * %dataBlockLength + 14);
					totalDispensersUsed = 			getWord(%line, %i * %dataBlockLength + 15);
					totalConsolesUsed = 			getWord(%line, %i * %dataBlockLength + 16);
					totalDoorsOpened = 				getWord(%line, %i * %dataBlockLength + 17);
					totalDoorsClosed = 				getWord(%line, %i * %dataBlockLength + 18);
					totalItemsGrabbed = 			getWord(%line, %i * %dataBlockLength + 19);
					totalItemsUsed = 				getWord(%line, %i * %dataBlockLength + 20);
					totalChestsOpened = 			getWord(%line, %i * %dataBlockLength + 21);
					totalLightSwitchesUsed = 		getWord(%line, %i * %dataBlockLength + 22);
					totalGuardModes = 				getWord(%line, %i * %dataBlockLength + 23);
				};
				$OnlineScoresList.add(%onlineRecord);
				%i++;
				%block = getWord(%line, %i * %dataBlockLength);	// Looking for %dataBlockLength pieces of data per record!
			}//echo("Found " @ $OnlineScoresList.getCount() @ " records!");
			// Got all data. Sort it!
			%swapped = true;
			while (%swapped)
			{//echo("%swapped =" SPC %swapped);//echo("$OnlineScoresList.getCount() =" SPC $OnlineScoresList.getCount());
				%swapped = false;
				for (%i = 0; %i < $OnlineScoresList.getCount() - 1; %i++)
				{
					%currentRecord = $OnlineScoresList.getObject(%i);
					%nextRecord = $OnlineScoresList.getObject(%i + 1);
					if (%currentRecord.score < %nextRecord.score)
					{
						$OnlineScoresList.reorderChild(%nextRecord, %currentRecord);  
						%swapped = true;
					}
				}
			}// Debug output!/*for (%i = 0; %i < $OnlineScoresList.getCount(); %i++){ echo("Record " @ %i + 1 @ " score = " @ $OnlineScoresList.getObject(%i).score); }*/
			// Re-init.
			$gettingServerData = false;
			$getServerLine = 0;
		}
	}
}