<?php
//FOR DEBUG
mysqli_report(MYSQLI_REPORT_ERROR);

require("header.php");
	//MySQL 更新データの仕様
	// URL引数でUserID(uid)を渡す。
	// update.php?uid=xxx
	//
	// 

$db = new mysqli('localhost', DATABASE_USER, DATABASE_PWD, DATABASE_NAME);
if (mysqli_connect_error()) {
	responseError();
}
// 文字化け防止
$db->set_charset("utf8");

if(isset($_GET['uid']) && isset($_GET['action'])){
	$uid = $_GET['uid'];
	$action = $_GET['action'];
	//ステージ名の取得
	$stmt = $db->prepare(QUERY_SELECT_USER_STAGE_AND_TIMESTAMP);
	$stmt->bind_param(QUERY_SELECT_USER_STAGE_AND_TIMESTAMP_TYPES, $uid);
	$stmt->execute();
	if($stmt->errno != 0){
		exit("error0");
	}
	//クエリ成功
	$stmt->store_result();
	if($stmt->num_rows == 0){
		exit("error1");
	}
	$stmt->bind_result($stgName, $lastTimeStamp);
	$stmt->fetch();
	$stmt->close();
	
	$request_param = array();
	foreach ( $_POST as $k => $v){
		// URL デコードを行い値を連想配列に格納する
		$request_param{"$k"} = urldecode($v);
	}
	
	if(strcmp($action, 'add') == 0){
		//オブジェクトをデータベースに追加
		//postデータは、"origin.x,origin.y,speed.x,speed.y,className,attribute,constructorArgs"
		//retvデータは、"[timestamp,[objectID, ...], [[objectID,origin.x,origin.y,speed.x,speed.y,className,attribute,constructorArgs]...]]"
		$retarray = array();
		foreach($request_param as $aParam){
			$subparam = explode('|', $aParam);
			$stmt = $db->prepare(QUERY_ADD_OBJECT);
			$stmt->bind_param(QUERY_ADD_OBJECT_TYPES, $subparam[0], $subparam[1], $subparam[2], $subparam[3], $stgName, $subparam[4], $subparam[5], $subparam[6],$uid, getTimeStampMs(), getTimeStampMs());
			$stmt->execute();
			if($stmt->errno != 0){
				exit("error3");
			}
			array_push($retarray, $db->insert_id);
			$stmt->close();
		}
		//出力
		echo("[" . getTimeStampMs() . ",[");
		foreach($retarray as $v){
			echo($v . ",");
		}
		echo("],");
		echo(getAllOtherUserObjectArrayString($db, $uid, $stgName));
		echo("]");
	} else if(strcmp($action, 'refresh') == 0){
		//渡されたオブジェクトのデータ更新
		//postデータは、"objectID,origin.x,origin.y,speed.x,speed.y,attribute"
		foreach($request_param as $aParam){
			$subparam = explode('|', $aParam);
			$stmt = $db->prepare(QUERY_UPDATE_STAGE_OBJECT);
			$stmt->bind_param(QUERY_UPDATE_STAGE_OBJECT_TYPES, $subparam[1], $subparam[2], $subparam[3], $subparam[4], $subparam[5], getTimeStampMs(), $stgName, $subparam[0]);
			$stmt->execute();
			if($stmt->errno != 0){
				exit("error14");
			}
			$stmt->close();
		}
		
		
		//retv[2]:追加リスト
		//[objectID,origin.x,origin.y,speed.x,speed.y,className,attribute,constructorArgs]"
		$retv2 = array();
		$stmt = $db->prepare(QUERY_SELECT_ADDED_OBJECT);
		$stmt->bind_param(QUERY_SELECT_ADDED_OBJECT_TYPES, $stgName, $uid, $lastTimeStamp);
		$stmt->execute();
		if($stmt->errno != 0){
			exit("error7");
		}
		$result = $stmt->get_result();
		for($i = 0; $i < $result->num_rows; $i++){
			$tmpAry = $result->fetch_array(MYSQLI_NUM);
			array_push($retv2, "[" . $tmpAry[0] . "," . $tmpAry[1] . "," . $tmpAry[2] . "," . $tmpAry[3] . "," . $tmpAry[4] . ",\"" . $tmpAry[5] . "\",\"" . $tmpAry[6] . "\",\"" . $tmpAry[7] . "\"," . $tmpAry[8] . "]");
		}
		$stmt->close();
		//retv[1]:更新リスト
		//[objectID,origin.x,origin.y,speed.x,speed.y,className,attribute]"
		$retv1 = array();
		$stmt = $db->prepare(QUERY_SELECT_UPDATED_OBJECT);
		if(!$stmt){
			exit("error:" . $db->error);
		}
		$stmt->bind_param(QUERY_SELECT_UPDATED_OBJECT_TYPES, $stgName, $uid, $lastTimeStamp, $lastTimeStamp);
		$stmt->execute();
		if($stmt->errno != 0){
			exit("error8");
		}
		$result = $stmt->get_result();
		for($i = 0; $i < $result->num_rows; $i++){
			echo(" ");
			$tmpAry = $result->fetch_array(MYSQLI_NUM);
			array_push($retv1, "[" . $tmpAry[0] . "," . $tmpAry[1] . "," . $tmpAry[2] . "," . $tmpAry[3] . "," . $tmpAry[4] . ",\"" . $tmpAry[5] . "\",\"" . $tmpAry[6] . "\"]");
		}
		$stmt->close();
		//retv[3]:削除リスト
		//objectID
		$retv3 = array();
		$stmt = $db->prepare(QUERY_SELECT_DELETED_OBJECT);
		$stmt->bind_param(QUERY_SELECT_DELETED_OBJECT_TYPES, $stgName, $uid, $lastTimeStamp);
		$stmt->execute();
		if($stmt->errno != 0){
			exit("error9");
		}
		$result = $stmt->get_result();
		for($i = 0; $i < $result->num_rows; $i++){
			$tmpAry = $result->fetch_array(MYSQLI_NUM);
			array_push($retv3, $tmpAry[0]);
		}
		$stmt->close();
		//retv[4]:ユーザーリスト
		//userID, userName
		$retv4 = array();
		$stmt = $db->prepare("select id, name from authUserTable");
		$stmt->execute();
		if($stmt->errno != 0){
			exit("error5673");
		}
		$result = $stmt->get_result();
		for($i = 0; $i < $result->num_rows; $i++){
			$tmpAry = $result->fetch_array(MYSQLI_NUM);
			array_push($retv4, $tmpAry[0] . ":\"" . $tmpAry[1] . "\"");
		}
		$stmt->close();
		//出力
		echo("[");
		echo(getTimeStampMs());
		echo(",[");
		foreach($retv1 as $v){
			echo($v . ",");
		}
		echo("],[");
		foreach($retv2 as $v){
			echo($v . ",");
		}
		echo("],[");
		foreach($retv3 as $v){
			echo($v . ",");
		}
		echo("],{");
		foreach($retv4 as $v){
			echo($v . ",");
		}
		echo("}]");
	}
	updateUserTimestamp($db, $uid);
	exit();
}

function getAllOtherUserObjectArrayString($db, $userID, $stageName)
{
	$retary = array();
	$stmt = $db->prepare(QUERY_SELECT_ALL_OTHER_USER_OBJECT);
	$limittime = getTimeStampMs() - OBJECT_ALIVE_TIME_MS;
	$stmt->bind_param(QUERY_SELECT_ALL_OTHER_USER_OBJECT_TYPES, $stageName, $userID, $limittime);
	$stmt->execute();
	if($stmt->errno != 0){
		exit("error745");
	}
	$result = $stmt->get_result();
	for($i = 0; $i < $result->num_rows; $i++){
		$tmpAry = $result->fetch_array(MYSQLI_NUM);
		array_push($retary, "[" . $tmpAry[0] . "," . $tmpAry[1] . "," . $tmpAry[2] . "," . $tmpAry[3] . "," . $tmpAry[4] . ",\"" . $tmpAry[5] . "\",\"" . $tmpAry[6] . "\",\"" . $tmpAry[7] . "\"," . $tmpAry[8] . "]");
	}
	$stmt->close();
	$retstr = "[";
	foreach($retary as $v){
		$retstr = $retstr . $v . ",";
	}
	$retstr = $retstr . "]";
	return $retstr;
}

//
// response
//
//[
//	[timestamp],
//	
//]
function responseError()
{
	exit("[0, 0, null];");
}

?>