<?php
	
	//
	// Description:
	//
	// Expects connection.inc.php to have correct database information supplied.
	//
	// Request variable should supply 'screen' and 'action' variables, and
	// optionally 'p1', 'p2', and 'p3' variables as well (all strings, length<=50).
	//
	// The preprocess method can be altered to inject arbitrary data.
	// The `preprocess` method uses robot movement/drawer models and
	// some gaussian code, to select time for these actions, which
	// are then reflected both in the database as well as a javascript
	// countdown timer.
	//
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	// Utility functions for stochasticity
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	
	// used for very small variance
	define( 'ZERO', 0.0001 );
	
	// following functions copied from: http://php.net/manual/en/function.rand.php
	
	function gauss()
	{   // N(0,1)
		// returns random number with normal distribution:
		//   mean=0
		//   std dev=1
		
		// auxilary vars
		$x=random_0_1();
		$y=random_0_1();
		
		// two independent variables with normal distribution N(0,1)
		$u=sqrt(-2*log($x))*cos(2*pi()*$y);
		$v=sqrt(-2*log($x))*sin(2*pi()*$y);
		
		// i will return only one, cause only one needed
		return $u;
	}
	
	function gauss_ms( $m=0.0, $s=1.0 )
	{   // N(m,s)
		// returns random number with normal distribution:
		//   mean=m
		//   std dev=s
		
		return gauss()*(float)$s+(float)$m;
	}
	
	function random_0_1()
	{   // auxiliary function
		// returns random number with flat distribution from 0 to 1
		return (float)rand()/(float)getrandmax();
	}
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	
	
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	// Generic function for preprocessing event data before sending up to the database.
	// Basic idea is to condition on the "screen" request variable and intercede as necessary.
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function preprocess( &$data )
	{
		$ret = array();
		
		if ( $data['screen'] == 'goto' )
		{
			// robotic motion models ( 'start' => array( 'end' => array( 'm'=>mean, 's'=>std. dev ) ) )
			$model = array();
			$model['drawers'] = array(
				'kitchen'=>array(	'm'=>48,	's'=>17 ),
				'couch'=>array(		'm'=>50,	's'=>6 ),
				'desk'=>array(		'm'=>37,	's'=>ZERO ),
			);
			$model['kitchen'] = array(
				'drawers'=>array(	'm'=>44,	's'=>10 ),
				'couch'=>array(		'm'=>62,	's'=>17 ),
				'desk'=>array(		'm'=>40,	's'=>5 ),
			);
			$model['couch'] = array(
				'drawers'=>array(	'm'=>43,	's'=>ZERO ),
				'kitchen'=>array(	'm'=>54,	's'=>8 ),
				'desk'=>array(		'm'=>39,	's'=>2 ),
			);
			$model['desk'] = array(
				'drawers'=>array(	'm'=>34,	's'=>3 ),
				'kitchen'=>array(	'm'=>39,	's'=>3 ),
				'couch'=>array(		'm'=>50,	's'=>11 ),
			);
			
			// these get added to the inserted row
			$r = intval( round( gauss_ms( $model[ $data['p1'] ][ $data['p2'] ]['m'], $model[ $data['p1'] ][ $data['p2'] ]['s'] ) ) );
			$data['p3'] = $r;
			
			// and prepend countdown javascript code
			$ret[] = '<label id="countdown_time"></label>';
			$ret[] = '<script type="text/javascript">javascript_countdown.init( ' . $r . ', \'countdown_time\', \'available\' );</script>';
		}
		else if ( $data['screen'] == 'drawer' )
		{
			// robotic drawer models ( 'operation' => array( 'm'=>mean, 's'=>std. dev ) )
			$model = array();
			$model['close'] = array( 'm'=>2, 's'=>ZERO );
			$model['open'] = array( 'm'=>2, 's'=>ZERO );
			
			// these get added to the inserted row
			$r = intval( round( gauss_ms( $model[ $data['p1'] ]['m'], $model[ $data['p1'] ]['s'] ) ) );
			$data['p2'] = $r;
			
			// and prepend countdown javascript code
			$ret[] = '<label id="countdown_time"></label>';
			$ret[] = '<script type="text/javascript">javascript_countdown.init( ' . $r . ', \'countdown_time\', \'available\' );</script>';
		}
		
		return $ret;
	}
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	
	// contains status messages (initially errors), if any
	$status = array();
	
	// contains preprocess code to display (e.g. countdown timer)
	$pre = array();
	
	// request variables => required?
	$fields = array( 'screen'=>true, 'action'=>true, 'p1'=>false, 'p2'=>false, 'p3'=>false );
	$data = array();
	foreach ( $fields as $f_key => $f_req )
	{
		$data[ $f_key ] = '';
		if ( isset( $_GET[ $f_key ] ) )
		{
			$data[ $f_key ] = trim( $_GET[ $f_key ] );
		}
		else if ( $f_req )
		{
			$status[] = array( 'Lacking data: ' . $f_key, true );
		}
	}
	
	// if all required variables provided...
	if ( empty( $status ) )
	{
		// preprocess
		$pre = preprocess( $data );
		{
			// package to show final data state
			$d = array();
			foreach ( $data as $k=>$v )
			{
				if ( strlen( $v ) )
				{
					$d[] = ( $k . '=' . $v );
				}
			}
			
			$status[] = array( 'Data: ' . implode( ', ', $d ), false );
		}
		
		// bring in the database connection information
		require 'connection.inc.php';
		if ( isset ( $conn_info ) )
		{
			// connect to the database
			$db = @mysql_connect( $conn_info['host'], $conn_info['user'], $conn_info['pass'] );
			
			if ( !$db ) 
			{
				$status[] = array( 'Connection error: ' . mysql_error(), true );
			}
			else
			{
				if ( !mysql_select_db( $conn_info['db'], $db ) )
				{
					$status[] = array( 'Database selection error: ' . mysql_error(), true );
				}
				else
				{
					$status[] = array( 'DB: connected', false );
					
					// insert the event
					$cols = array();
					$vals = array();
					foreach ( $data as $dk => $dv )
					{
						$cols[] = ( '`event_' . $dk . '`' );
						$vals[] = ( "'" . mysql_escape_string( $dv ) . "'" );
					}
					$sql = ( 'INSERT INTO events (' . implode( ',', $cols ) . ') VALUES (' . implode( ',', $vals ) . ')' );
					
					// provide status
					if ( mysql_query( $sql, $db ) )
					{
						$status[] = array( 'Query: successful', false );
					}
					else
					{
						$status[] = array( 'Query error: ' . mysql_error() . ' [' . htmlentities( $sql ) . ']', true );
					}
				}
			}
		}
		else
		{
			$status[] = array( 'Could not find connection information.', true );
		}
	}
	
?>

<!DOCTYPE html>
<html>
	<head>
	<title>Robot Event</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
		<link rel="stylesheet" href="iui/iui.css" type="text/css" />
		<link rel="stylesheet" title="Default" href="iui/t/default/default-theme.css"  type="text/css"/>
		<script type="application/x-javascript" src="iui/iui.js"></script>
		<script type="text/javascript" src="countdown.js"></script>
	</head>
	<body>
		<div class="toolbar">
			<h1 id="pageTitle"></h1>
		</div>

		<form class="panel" id="index" name="index" title="Result" selected="true" method="GET" action="index.php">
			<fieldset>
				<?php
					if ( !empty( $pre ) )
					{
				?>
						<div class="row">
						<?php
							echo implode( '<br />', $pre );
						?>
						</div>
				<?php
					}
				?>

				<div class="row">
					<?php
						foreach ( $status as $s )
						{
							echo ( '<p' . ( ( $s[1] )?( ' style="font-weight: bold"' ):('') ) . '>' . htmlentities( $s[0] ) . '</p>' );
						}
					?>
				</div>
			</fieldset>
			<a class="whiteButton" href="javascript:index.submit()">Home</a>
		</form>
		

	</body>
</html>
