<?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.
*/

require(__DIR__ ."/inc/envsetup.php");

$settings = new SiWeather\Webservice\WebserviceConfig();

/**
	* @brief Handles the stations (list) REST requests
	*/
function stations(){
	$stations = Array();

	$db = new SiWeather\Webservice\DatabaseHandler();
	if(!$db->connect()){
		echo json_encode
		(
			[
				"result" => "failed",
				"message" => "Could not connect to the database",
			]
		);
		return;
	}
	$db->exec("BEGIN");

	$sqlStatement = $db->prepare("SELECT stations.uuid as uuid, stations.name as name, X(stations.location) as longitude, Y(stations.location) as latitude, cities.name as city FROM stations, cities WHERE stations.city=cities.id");
	if(!$sqlStatement){
		$db->exec("ROLLBACK");
		echo json_encode
		(
			[
				"result" => "failed",
				"message" => "Could not fetch stations from database",
			]
		);
		return;
	}
	$result = $sqlStatement->execute();
	while($row = $result->fetchArray()){
		$station = Array();
		$station["uuid"] = $row["uuid"];
		$station["name"] = $row["name"];
		$station["longitude"] = $row["longitude"];
		$station["latitude"] = $row["latitude"];
		$station["city"] = $row["city"];
// 		$station["values"] = Array();
// 		$station["values"][] = "temperature";
// 		$station["values"][] = "humidity";
		$station["url"] = "stations/". $station["uuid"];
		$stations[] = $station;
	}
	$db->exec("COMMIT");

	echo json_encode($stations);
}

/**
  * @brief Registers a new weather station
  *
  * @note Call this function with a big timeout > 2seconds, because we use another webservice
  *       to fetch location data. This fetch runs already 2seconds.
	* @note Requires php-pecl-uuid
  */
function stationsRegister(){
	$geoLocationRadius = 5;

	try{
		$app = \Slim\Slim::getInstance("siweather");
		$body = $app->request->getBody();
		$json = json_decode($body, true);

		$app->response()->header("Content-Type", "application/json");

		$expectedKeys = array("name", "city", "longitude", "latitude", "email");
		$missingKeys = array();
		foreach($expectedKeys as $key){
			if(!array_key_exists($key, $json))
				$missingKeys[] = $key;
		}
		if(count($missingKeys) > 0){
			echo json_encode
			(
				[
					"result" => "missingkeys",
					"message" => "Your request misses the following keys: ". implode(", ", $missingKeys),
				]
			);
			return;
		}

		if(!SiWeather\Webservice\Location::ValidLatitude($json["latitude"])){
			echo json_encode
			(
				[
					"result" => "invalid latitude",
					"message" => "Your specified an invalid latitude: ". $json["latitude"],
				]
			);
			return;
		}
		if(!SiWeather\Webservice\Location::ValidLongitude($json["longitude"])){
			echo json_encode
			(
				[
					"result" => "invalid longitude",
					"message" => "Your specified an invalid longitude: ". $json["longitude"],
				]
			);
			return;
		}
		if(empty($json["email"]) || !filter_var($json["email"], FILTER_VALIDATE_EMAIL)){
			echo json_encode
			(
				[
					"result" => "invalid email",
					"message" => "Your specified an invalid email address: ". $json["email"],
				]
			);
			return;
		}

		$errorMessage = "";
		$locations = SiWeather\Webservice\GeoLocator::locations($json["latitude"], $json["longitude"], $geoLocationRadius, $errorMessage);
		if(!$locations || count($locations) < 1){
			error_log($errorMessage);
			echo json_encode
			(
				[
					"result" => "unprovenlocation",
					"message" => "Could not check the city (". $json["city"] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send with help of your city and geo coordinates. Please make sure, your data is correct.",
				]
			);
			return;
		}
		else{
			$validatedLocation = false;
			foreach($locations as $location){
				if($location->city() == $json["city"]){
					$validatedLocation = $location;
				}
			}
			if(!$validatedLocation){
				$message  = "The city (". $json[city] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send, does not suite with locations we found at your given location (city, latitude, longitude):\n";
				foreach($locations as $location){
					$message .= "    ". $location->city() .": ". $location->latitude() .", ". $location->longitude() ."\n";
				}
				$message .= " Please make sure, your data is correct.";

				echo json_encode
				(
					[
						"result" => "unprovenlocation",
						"message" => $message,
					]
				);
				return;
			}
		}

		$db = new SiWeather\Webservice\DatabaseHandler();
		if(!$db->connect()){
			echo json_encode
			(
				[
					"result" => "failed",
					"message" => "Could not connect to the database",
				]
			);
			return;
		}
		$db->exec("BEGIN");

		// find out, if the city is already there
		$cityId = -1;
		$sqlStatement = $db->prepare("SELECT id FROM cities WHERE name=:name AND location=:location");
		if(!$sqlStatement){
			$db->exec("ROLLBACK");
			echo json_encode
			(
				[
					"result" => "failed",
					"message" => "Could not fetch city from database",
				]
			);
			return;
		}
		$sqlStatement->bindValue(":name", $validatedLocation->city());
		$sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
		$result = $sqlStatement->execute();
		if($result->numColumns() && $result->columnType(0) != SQLITE3_NULL){
			error_log("not cool");
			$row = $result->fetchArray();
			$cityId = $row[0];
			error_log($row[0]);
		}
		else{
			$sqlStatement = $db->prepare("INSERT INTO cities (name, location) VALUES(:name, GeomFromText(:location, 4326))");
			if(!$sqlStatement){
				$db->exec("ROLLBACK");
				echo json_encode
				(
					[
						"result" => "failed",
						"message" => "Could insert city into the database",
					]
				);
				return;
			}
			$sqlStatement->bindValue(":name", $validatedLocation->city());
			$sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
			$sqlResult = $sqlStatement->execute();
			if(!$sqlResult){
				error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage());
				$db->exec("ROLLBACK");
				echo json_encode
				(
					[
						"result" => "failed",
						"message" => "Could not add city to the database",
					]
				);
				return;
			}
			$cityId = $db->lastInsertRowId();
		}
		if($cityId < 0){
			error_log("Failed to select city from the database: ". $db->lastDatabaseErrorMessage());
			$db->exec("ROLLBACK");
			echo json_encode
			(
				[
					"result" => "failed",
					"message" => "Could not select city from the database",
				]
			);
			return;
		}

		// insert station
		$uuid = uuid_create(4);
		$sqlStatement = $db->prepare("INSERT INTO stations (name, city, uuid, ownerMail, location) VALUES(:name, :city, :uuid, :ownerMail, GeomFromText(:location, 4326))");
		if(!$sqlStatement){
			$db->exec("ROLLBACK");
			echo json_encode
			(
				[
					"result" => "failed",
					"message" => "Could insert station into the database",
				]
			);
			return;
		}
		$sqlStatement->bindValue(":name", $json["name"]);
		$sqlStatement->bindValue(":city", $cityId);
		$sqlStatement->bindValue(":uuid", $uuid);
		$sqlStatement->bindValue(":ownerMail",$json["email"]);
		$sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
		$sqlResult = $sqlStatement->execute();
		if(!$sqlResult){
			error_log("Failed to add station to the database: ". $db->lastDatabaseErrorMessage());
			$db->query("ROLLBACK");
			echo json_encode
			(
				[
					"result" => "failed",
					"message" => "Could not add station to the database",
				]
			);
			return;
		}

		// finish transaction
		$db->exec("COMMIT");

		echo json_encode
		(
			[
				"result" => "success",
				"uuid" => $uuid,
			]
		);
	}
	catch(Exception $exception){
		error_log("Caught exception handling request stationsRegister: ". $exception->getMessage());
		$app->response()->status(400);
		$app->response()->header("X-Status-Reason", $exception->getMessage());
	}
}

$app = new \Slim\Slim
(
	array
	(
		"mode" => $settings->getConfig("mode"),
	)
);
$app->setName("siweather");

// Only invoked if mode is "production"
$app->configureMode('production', function () use ($app) {
    $app->config(array(
        "log.enable" => true,
        "log.level" => \Slim\Log::WARN,
        "debug" => false,
    ));
});
// Only invoked if mode is "development"
$app->configureMode('development', function () use ($app) {
    $app->config(array(
        "log.enable" => true,
        "log.level" => \Slim\Log::DEBUG,
        "debug" => true
    ));
});

$app->notFound(function () use ($app) {
	$html = "";
    if($app->config("debug")){
        ob_start();
        phpinfo( INFO_VARIABLES ^ INFO_ENVIRONMENT );
        $html = ob_get_contents();
        ob_end_clean();
    }
    $app->render("404.php", array("dump" => $html));
});

$app->get("/setup", function () use ($app){
	$app->render("setup.php");
});

$app->get("/stations", "stations");
$app->post("/stations/register", "stationsRegister");

$app->run();

?>
