<?php
// 一行区切り "~"
// 項目区切り ","

//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//	自動でクラスを参照する
//	関数名	：	__autoload()
//	備考	：	参照先は./class/XXX.phpとする
//	更新	：	2012/10/19 KMK-Teraoka
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
function __autoload($className)
{
	$fPath = "./class/" . str_replace("_", "/", $className) . ".php";
	require_once $fPath;
}

//===============================================
//	DEBUG_MODE
//	備考		：	
//	更新		：	2012/11/29 KMK-Teraoka
//===============================================
define("DEBUG_MODE", "0");
Debug::setMode(DEBUG_MODE);
if (DEBUG_MODE == 1)
{
	Stopwatch::start();
}

//===============================================
//	CommonUtilities
//	備考		：	
//	更新		：	2012/11/29 KMK-Teraoka
//===============================================
$HOST = "192.168.100.153";
$DB = "ansys";
$USER = "postgres";
$PASS = "am#71ZJ*";
$LOG_FILE = "./log/recv_positions.log";

try
{
	$_log = new Log($LOG_FILE);
	
	//===============================================
	//	POST、GETパラメータの受け取り
	//	備考		：	
	//	更新		：	2012/11/29 KMK-Teraoka
	//===============================================
	if (DEBUG_MODE == 1)
	{
		extract($_POST);
		extract($_GET);
		Debug::writes($_POST);
	}
	$constId = isset($_POST["const_id"]) ? htmlspecialchars($_POST["const_id"]) : "";
	$appId = isset($_POST["app_id"]) ? htmlspecialchars($_POST["app_id"]) : "";
	$androidId = isset($_POST["android_id"]) ? htmlspecialchars($_POST["android_id"]) : "";
	$positions = isset($_POST["positions"]) ? htmlspecialchars($_POST["positions"]) : "";
	
	$_log->write("CONST_ID->". $constId. "\n");
	$_log->write("APP_ID->". $appId. "\n");
	$_log->write("ADNROID_ID->". $androidId. "\n");
	$_log->write("POSITIONS->". $positions. "\n");
	//$constId = "2";
	//$appId = "2";
	//$androidId="961b1a243878b000";
	//$positions = "36.9079452,139.93820552,241.0,1354165853407,0.0\\^36.90794527,139.9382055,246.0,1354165854407,0.0";
	
	if (strcmp($androidId, "") == 0)
	{
		throw new Exception("管理IDが指定されていません");
	}
	
	//================================================
	//	データベース接続
	//	備考		：	
	//	更新		：	2012/11/29 KMK-Teraoka
	//================================================
	$conn = pg_connect("
		host	=	". $HOST. "
		dbname	=	". $DB. "
		user	=	". $USER. "
		password=	". $PASS. "
	");
	if (!$conn)
	{
		throw new Exception("データベースへの接続に失敗しました");
	}
	
	//===============================================
	//	Positionsを項目毎に分割
	//	備考		：	
	//	更新		：	2012/11/29 KMK-Teraoka
	//===============================================
	$posiData = array();
	
	$sepRow = explode("#", $positions);
	for($iCount = 0; $iCount < count($sepRow); $iCount++)
	{
		$sepColumn = explode(",", $sepRow[$iCount]);
		$posiData[$iCount]["lat"] = $sepColumn[0];
		$posiData[$iCount]["lon"] = $sepColumn[1];
		$posiData[$iCount]["acc"] = $sepColumn[2];
		$posiData[$iCount]["time"] = $sepColumn[3] / 1000.0;
		$posiData[$iCount]["speed"] = $sepColumn[4];
		if (count($sepColumn) > 5)
		{
			$posiData[$iCount]["direction"] = $sepColumn[5];
		}
		else
		{
			$posiData[$iCount]["direction"] = 0;
		}
	}
	Debug::writes($posiData);
	
	for($iCount = 0; $iCount < count($posiData); $iCount++)
	{
		// 位置管理テーブルへ登録
		$insTsHis = "INSERT INTO qgis.ts_his_measure";
		$insTsHis .= " (android_id, const_id, app_id, lat, lon, acc, spd, mesdatetime, regdatetime, direction)";
		$insTsHis .= " VALUES";
		$insTsHis .= " ('". $androidId. "','". $constId. "','". $appId. "','". $posiData[$iCount]["lat"]. "','". $posiData[$iCount]["lon"]. "','". $posiData[$iCount]["acc"]. "','". $posiData[$iCount]["speed"]. "',to_timestamp('". $posiData[$iCount]["time"]. "'),current_timestamp, '". $posiData[$iCount]["direction"]. "')";
		$insTsHis .= ";";
		$_log->write($insTsHis. "\n");
		Debug::write($insTsHis);
		if (!($resTsHis = pg_query($conn, $insTsHis)))
		{
			throw new Exception("位置管理テーブルへの登録に失敗<br />". $resTsHis. "<br />". pg_last_error(). "<br />");
		}
		
		// 端末管理テーブルに登録または更新
		if ($iCount == (count($posiData) - 1))
		{
			$selTsTerm = "SELECT * FROM qgis.ts_terminal";
			$selTsTerm .= " WHERE android_id='". $androidId. "'";
			$selTsTerm .= " AND const_id='". $constId. "'";
			$selTsTerm .= " AND app_id='". $appId. "'";
			$selTsTerm .= ";";
			$_log->write($selTsTerm. "\n");
			if (!($resTsTerm = pg_query($conn, $selTsTerm)))
			{
				throw new Exception("端末管理テーブルの検索に失敗<br />". $resTsTerm. "<br />". pg_last_error(). "<br />");
			}
			
			$refTsTerm = "";
			
			if (0 == pg_num_rows($resTsTerm))
			{
				//================================================
				//	端末名称の取得
				//	備考		：	
				//	更新		：	2012/11/29 KMK-Teraoka
				//================================================
				$selTermName = "SELECT terminal_name FROM apc_common.terminals";
				$selTermName .= " WHERE android_id='". $androidId. "'";
				$selTermName .= " AND del_flg='f'";
				$selTermName .= " ORDER BY upddatetime DESC";
				$selTermName .= ";";
				Debug::write($selTermName);
				if (!($resTermName = pg_query($conn, $selTermName)))
				{
					throw new Exception("データ取得に失敗<br />". $resTermName. "<br />". pg_last_error(). "<br />");
				}
				$rowTermName = pg_fetch_array($resTermName, 0, PGSQL_ASSOC);
				$termName = $rowTermName["terminal_name"];
				
				// INSERT
				$refTsTerm = "INSERT INTO qgis.ts_terminal";
				$refTsTerm .= " (android_id, terminal_name, const_id, app_id, lat, lon, acc, spd, mesdatetime, upddatetime, regdatetime, direction)";
				$refTsTerm .= " VALUES";
				$refTsTerm .= " ('". $androidId. "','". $termName. "','". $constId. "','". $appId. "','". $posiData[$iCount]["lat"]. "','". $posiData[$iCount]["lon"]. "','". $posiData[$iCount]["acc"]. "','". $posiData[$iCount]["speed"]. "',to_timestamp('". $posiData[$iCount]["time"]. "'),current_timestamp,current_timestamp,'". $posiData[$iCount]["direction"]. "')";
				$refTsTerm .= ";";
			}
			else
			{
				// UPDATE
				$refTsTerm = "UPDATE qgis.ts_terminal";
				$refTsTerm .= " SET lat='". $posiData[$iCount]["lat"]. "',";
				$refTsTerm .= " lon='". $posiData[$iCount]["lon"]. "',";
				$refTsTerm .= " acc='". $posiData[$iCount]["acc"]. "',";
				$refTsTerm .= " spd='". $posiData[$iCount]["speed"]. "',";
				$refTsTerm .= " direction='". $posiData[$iCount]["direction"]. "',";
				$refTsTerm .= " mesdatetime=to_timestamp('". $posiData[$iCount]["time"]. "'),";
				$refTsTerm .= " upddatetime=current_timestamp";
				$refTsTerm .= " WHERE android_id='". $androidId. "'";
				$refTsTerm .= " AND const_id='". $constId. "'";
				$refTsTerm .= " AND app_id='". $appId. "'";
				$refTsTerm .= ";";
			}
			Debug::write($refTsTerm);
			$_log->write($refTsTerm. "\n");
			if (!($resRefTsTerm = pg_query($conn, $refTsTerm)))
			{
				throw new Exception("データ更新に失敗<br />". $resRefTsTerm. "<br />". pg_last_error(). "<br />");
			}
		}
	}
}
catch(Exception $exc)
{
	$_log->write($exc->getMessage(). "\n");
}

//===============================================
//	Postgresql終了処理
//	備考		：	
//	更新		：	2012/10/19 KMK-Teraoka
//===============================================
pg_close($conn);

?>
