<?php
/*
    Copyright (C) 2015 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    MA 02110-1301  USA.
*/

class SpatialiteTest extends PHPUnit_Framework_TestCase
{
	public static function setUpBeforeClass()
	{
		global $testconfig;

		$file = __DIR__ ."/testconfig/testconfig.php";
		self::assertFileExists($file);
		require($file);
		require_once($testconfig["webserviceDirectory"] ."/SiWeather/Webservice/WebserviceConfig.php");
		self::$_webserviceConfig = new SiWeather\Webservice\WebserviceConfig();
		self::assertNotNull(self::$_webserviceConfig);
		
		self::$_databaseFile = tempnam(sys_get_temp_dir(), "siw");
		# PDO SQlite is not able to load extensions (caused by the sqlite pdo driver)
		# therefore we use PHP SQlite module
		self::$_database = new SQLite3(self::$_databaseFile);
	}
	
	public static function tearDownAfterClass()
	{
		self::assertTrue(self::$_database->close());
		self::assertTrue(unlink(self::$_databaseFile));
		self::$_database = null;
		self::$_databaseFile = null;
	}

	public function testLoadSpatialite()
	{
		$this->assertInstanceOf("SQLite3", self::$_database);

		# loading SpatiaLite as an extension
		if(!self::$_database->loadExtension(self::$_webserviceConfig->getConfig("spatialiteExtension"))){
			echo "Could not load SpatialLite extension: ". self::$_database->lastErrorMsg();
			return;
		}
		
		$this->assertTrue(self::$_database->exec("BEGIN"));
		$this->assertTrue(self::$_database->exec("SELECT InitSpatialMetadata()"));
		$this->assertTrue(self::$_database->exec("COMMIT"));
		
		# reporting some version info
		$rs = self::$_database->query("SELECT spatialite_version()");
		$this->assertInstanceOf('SQLite3Result', $rs);
		$row = $rs->fetchArray();
		$this->assertInternalType("array", $row);
		$this->assertGreaterThan(1, count($row));
		$this->assertTrue(!empty($row[0]));
		$row = $rs->fetchArray();
		$this->assertTrue(!$row);
	}
	
	public function testDistance()
	{
		$this->assertInstanceOf("SQLite3", self::$_database);

		$table = "cities";
		
		# creating a POINT table
		$sql  = "CREATE TABLE ". $table ." (";
		$sql .= "id INTEGER NOT NULL PRIMARY KEY,";
		$sql .= "name TEXT NOT NULL)";
		$this->assertTrue(self::$_database->exec($sql));

		# creating a POINT Geometry column named center,
		# taking two coordinates in SRID 4326 (WGS84) format
		$sql  = "SELECT AddGeometryColumn(\"". $table ."\", ";
		$sql .= "\"center\", 4326, \"POINT\", \"XY\")";
		$this->assertTrue(self::$_database->exec($sql));
		
		# insert some cities
		# the center must be described in WKT (s. http://giswiki.org/wiki/WKT) format for a point.
		# Since we use WGS84 with SRID 4326 as a coordinate system, it expects POINT(LONGITUDE LATITUDE)
		# as values.
		# CITY, LATITUDE, LONGITUDE
		# example Berlin:
		#   52°31′7″N, 13°24′30″E
		#   --> 52.518611° Latitude and 13.408333° Longitude
		#   --> $values[] = array("name" => "Berlin", "latitude" => 52.518611, "longitude" => 13.408333);
		#   --> POINT("13.408333 52.518611")
		$values = array();
		$values[] = array("name" => "Berlin", 			"latitude" => 52.518611, 	"longitude" => 13.408333);
		$values[] = array("name" => "Potsdam", 			"latitude" => 52.395833, 	"longitude" => 13.061389);
		$values[] = array("name" => "Hamburg", 			"latitude" => 53.550556, 	"longitude" => 9.993333);
		$values[] = array("name" => "Dresden", 			"latitude" => 51.049259, 	"longitude" => 13.73836);
		$values[] = array("name" => "Cape Town",		"latitude" => -33.922667, 	"longitude" => 18.416689);
		$values[] = array("name" => "New York City", 	"latitude" => 40.712778, 	"longitude" => -74.005833);
		$values[] = array("name" => "Sydney", 			"latitude" => -33.85, 		"longitude" => 151.2);
		
		# distances in meter
		$distances = array();
		$distances["Berlin"] = array();
		$distances["Berlin"]["Potsdam"] = 27185;
		$distances["Berlin"]["Hamburg"] = 255518;
		$distances["Berlin"]["Dresden"] = 164954;
		$distances["Berlin"]["Cape Town"] = 9624137;
		$distances["Berlin"]["New York City"] = 6385266;
		$distances["Berlin"]["Sydney"] = 16092238;
		
		$distances["Potsdam"] = array();
		$distances["Potsdam"]["Hamburg"] = 242231;
		$distances["Potsdam"]["Dresden"] = 156823;
		$distances["Potsdam"]["Cape Town"] =9612288;
		$distances["Potsdam"]["New York City"] = 6370104;
		$distances["Potsdam"]["Sydney"] = 16118486;
		
		$distances["Hamburg"] = array();
		$distances["Hamburg"]["Dresden"] = 377003;
		$distances["Hamburg"]["Cape Town"] = 9760489;
		$distances["Hamburg"]["New York City"] = 6129909;
		$distances["Hamburg"]["Sydney"] = 16275543;
		
		$distances["Dresden"] = array();
		$distances["Dresden"]["Cape Town"] = 9459562;
		$distances["Dresden"]["New York City"] = 6478589;
		$distances["Dresden"]["Sydney"] = 16109156;
		
		$distances["Cape Town"] = array();
		$distances["Cape Town"]["New York City"] = 12564111;
		$distances["Cape Town"]["Sydney"] = 11013398;
		
		$distances["New York City"] = array();
		$distances["New York City"]["Sydney"] = 15988687;
		
		$this->assertTrue(self::$_database->exec("BEGIN"));
		$sql  = "INSERT INTO ". $table ." (name, center) VALUES(:name, GeomFromText(:center, 4326))";
		$sqlStatement = self::$_database->prepare($sql);
		foreach ($values as $value){
			$sqlStatement->clear();
			$this->assertEquals(3, count($value));
			$this->assertTrue($sqlStatement->bindValue(":name", $value["name"]));
			$this->assertTrue($sqlStatement->bindValue(":center", "POINT(". $value["longitude"] ." ". $value["latitude"] .")"));
			$this->assertInstanceOf("SQLite3Result", $sqlStatement->execute());
			$sqlStatement->reset();
		}
		$this->assertTrue(self::$_database->exec("COMMIT"));
		
		# check the inserts
		$sql  = "SELECT id, name, X(center) as longitude, Y(center) as latitude FROM ". $table ." WHERE name=:name";
		$sqlStatement = self::$_database->prepare($sql);
		foreach ($values as $value){
			$sqlStatement->clear();
			$this->assertEquals(3, count($value));
			$this->assertTrue($sqlStatement->bindValue(":name", $value["name"]));
			$result = $sqlStatement->execute();
			$this->assertInstanceOf("SQLite3Result", $result);
			while($row = $result->fetchArray()){
				$this->assertGreaterThan(4, count($row));
				$this->assertGreaterThan(-1, $row[0]);
				$this->assertEquals($value["name"], $row[1]);
				$this->assertEquals($value["longitude"], $row[2]);
				$this->assertEquals($value["latitude"], $row[3]);
			}
			$sqlStatement->reset();
		}

		# calculate the distances
		# Calling Distance() with three parameters, which returns distance in Meter
		$sql  = "SELECT t1.name, t2.name, Round(Distance(t1.center, t2.center, 1), 0) As distance";
		$sql .= "  FROM ". $table ." AS t1, ". $table ." AS t2";
		$sql .= "  WHERE t1.name=:from AND t2.name=:to";
		$sqlStatement = self::$_database->prepare($sql);
		foreach(array_keys($distances) as $start){
			foreach(array_keys($distances[$start]) as $end){
				$sqlStatement->clear();
				# Calculate distance from start --> end
				$this->assertTrue($sqlStatement->bindValue(":from", $start));
				$this->assertTrue($sqlStatement->bindValue(":to", $end));
				$result = $sqlStatement->execute();
				$this->assertInstanceOf("SQLite3Result", $result);
				while($row = $result->fetchArray()){
					$this->assertGreaterThan(3, count($row));
					$this->assertEquals($start, $row[0]);
					$this->assertEquals($end, $row[1]);
					# 0.5% difference of the distance is accepted
					$delta = abs($distances[$start][$end] - $row[2])/$distances[$start][$end];
					$this->assertLessThan(0.005, $delta, $start ." --> ". $end .":\n  Expected: ". $distances[$start][$end] ."\n  Is: ". $row[2]);
				}
				$sqlStatement->reset();
			}
		}
	}

	protected static $_databaseFile;
	protected static $_database;
	protected static $_webserviceConfig;
}
?>
