<?php
include_once("config.php");

try {
	if (!empty($_POST['tweet'])) {

		// POST['tweet'] should be a tweet
		$tweet = $_POST['tweet'];

		$tweet = urldecode($tweet);
		
		$tweet = mysql_real_escape_string($tweet);

		$now = date("Y-m-d H:i:s", time());

		$query 	=		"INSERT INTO";
		// table name
		$query	.= 		" `audioGameTweets` ";
		// columns 
		$query	.=		" (`id`, `tweet`, `date`) ";
		$query	.=		" VALUES ";
		// values of columns
		$query	.=		" (NULL, '{$tweet}', '{$now}') ";

		// actually post data
		$result = mysql_query($query, $connection);// or die(mysql_error());
	} else if (!empty($_POST['gettweets'])) {
		// get tweets from server or something
		
		if (urldecode($_POST['gettweets']) == "all") {
			$query = "SELECT ";
			$query .= " * ";
			$query .= " FROM ";
			$query .= " `audioGameTweets` ";
			
		} else if (urldecode($_POST['gettweets']) == "one") {
			$query = "SELECT ";
			$query .= " * ";
			$query .= " FROM ";
			$query .= " `audioGameTweets` ";
			$query .= " ORDER BY `id` DESC ";
			$query .= " LIMIT 1 ";
			
		} else {
			$amount = intval(urldecode($_POST['gettweets']));
			$query = "SELECT ";
			$query .= " * ";
			$query .= " FROM ";
			$query .= " `audioGameTweets` ";
			$query .= " ORDER BY `id` DESC ";
			$query .= " LIMIT ";
			$query .= $amount;
			
		}
		
		$result = mysql_query($query, $connection);
		
		if (!$result) {
			echo "Could not successfully run query";
		}
		
		if (mysql_num_rows($result) == 0) {
			echo "No rows found";
		}
		
		while ($row = mysql_fetch_assoc($result)) {
			echo $row['id'] . " " . $row['date'] . " " . $row['tweet'] . " ½ \n\r"; 
		}
		
		echo "END";
		
	} else if (!empty($_POST['nodes'])) {
		$nodes = urldecode($_POST['nodes']);
		$node1str = substr($nodes, 0, strpos($nodes, "-"));
		$node2str = substr($nodes, strpos($nodes, "-")+1);
		$node1 = intval($node1str);
		$node2 = intval($node2str);
		
		// apparently  not allowed to delete stuff.
		//$query = " DELETE FROM `audioGameNodes`; ";
		$query = " INSERT INTO ";
		$query .= " `audioGameNodes` ";
		// columns 
		$query	.=	" (`id`, `node1`, `node2`) ";
		$query	.=	" VALUES ";
		// values of columns
		$query	.=	" ('NULL', '{$node1}', '{$node2}') ";
		
		$result = mysql_query($query, $connection);
		echo "result: " . $result;
		
	} else if (!empty($_POST['getnodes'])) {
		$query = "SELECT ";
		$query .= " * ";
		$query .= " FROM ";
		$query .= " `audioGameNodes` ";
		$query .= " ORDER BY ";
		$query .= " `id` DESC ";
		$query .= " LIMIT 1 ";
			
		$result = mysql_query($query, $connection);
		while ($row = mysql_fetch_array($result)) {
			echo urlencode($row['node1'] . "n" . $row['node2']);
		}
	} else if (!empty($_POST['getLastMove'])) {
		// get all tweets since time() mod 5 seconds - 5, and before time() mod 5. (so it's a full sample of tweets)
		$query = "SELECT ";
		$query .= " * ";
		$query .= " FROM ";
		$query .= " `audioGameTweets` ";
		$startdate = date("Y-m-d H:i:s", floor(time()) - floor(time()) % 5 - 5 );
		$enddate = date("Y-m-d H:i:s", floor(time()) - floor(time()) % 5 );
		// sent to Unity to identify which command was run the last time and not run duplicate commands.
		$secondsForEchoing = date("s", floor(time()) - floor(time()) % 5 );
		$query .= " WHERE date BETWEEN '{$startdate}' AND '{$enddate}' ";
		
		$result = mysql_query($query, $connection);
		
		if ($result == FALSE) {
			echo "NULL Could not successfully run query (false)";
			
		} else {
			
			if (mysql_num_rows($result) == 0) {
				echo "NULL no results";
			} else {
				$players = array("mrs." => 0, "mr." => 0);
				$directions = array("west" => 0, "south" => 0, "east" => 0, "north" => 0, "roar" => 0, "meteor" => 0,"781236948762384673" => 0);
				// count words in tweets and return the most often found request.
				while ($row = mysql_fetch_array($result)) {
					$tweet = $row['tweet'];
					foreach (explode(" ", $tweet) as $word) {
						$word = strtolower($word);
						foreach ($players as $player => &$count) {
							if (strpos($word, $player) !== FALSE) {
								$count = $count + 1;
							}
						}
						foreach ($directions as $direction => &$count) {
							if (strpos($word, $direction) !== FALSE) {
								$count = $count + 1;
							}
						}
					}
				}
				
				$maxPlayer = "";
				$maxCount = 0;
				foreach ($players as $player=>$count) {
					if ($count > $maxCount) {
						$maxCount = $count;
						$maxPlayer = $player;
					}
				}
				$maxDirection = "";
				$maxCount = 0;
				foreach ($directions as $direction=>$count) {
					if ($count > $maxCount) {
						$maxCount = $count;
						$maxDirection = $direction;
					}
				}
				
				if ($maxPlayer != "" && $maxDirection != "") 
				{
					if ($maxPlayer == "mrs.") 
						$maxPlayer = "P1";
					else
						$maxPlayer = "P2";
					$maxDirection = strtoupper(substr($maxDirection, 0, 1)) . substr($maxDirection, 1);
					echo $secondsForEchoing . " " . $maxPlayer . " " . $maxDirection;
				} else {
					echo "NULL no maximum";
				}
			}
		}
	}
} catch (Exception $e) {
	echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// close connection. or not. test if it matters.
mysql_close();

?>