<?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();
// 	$station = Array();
// 	$station["id"] = "123456";
// 	$station["name"] = "Station Name";
// 	$station["longitude"] = 52.320;
// 	$station["latitude"] = 48;
// 	$station["city"] = "Krefeld";
// 	$station["values"] = Array();
// 	$station["values"][] = "temperature";
// 	$station["values"][] = "humidity";
// 	$station["url"] = "stations/". $station["id"];
// 	$stations[] = $station;
	echo json_encode($stations);
}

/**
  * @brief Registers a new weather station
  */
function stationsRegister(){
	try{
		$app = \Slim\Slim::getInstance("siweather");
		$body = $app->request->getBody();
		$json = json_decode($body, true);

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

		$expectedKeys = array("city", "longitude", "latitude");
		$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(array_key_exists("locationchecked", $json) && $json["locationchecked"]){
			// user has checked the location already and we add it now
			
		}

		$errorMessage = "";
		$location = SiWeather\Webservice\IpGeoLocator::locate($app->request->getIp(), $errorMessage);
		if(is_null($location)){
			error_log($errorMessage);
			echo json_encode
			(
				[
					"result" => "unprovenlocation",
					"message" => "Could not check the city (". $json["city"] .") and location (". $json["longitude"] .", ". $json["latitude"] .") you send with help of your ip address. Please make sure, your data is correct. If your data is correct, please resend your request with the keyword \"locationchecked = true\".",
				]
			);
			return;
		}
		elseif($location->city() != $json["city"]){
			echo json_encode
			(
				[
					"result" => "unprovenlocation",
					"message" => "The city (". $json[city] .") and location (". $json["longitude"] .", ". $json["latitude"] .") you send, does not suit with your ip address associtated location (city: ". $location->city() ."; Location: ". $location->longitude() .", ". $location->latitude() ."). If your data is correct, please resend your request with the keyword \"locationchecked = true\".",
				]
			);
			return;
		}

		echo json_encode($json);
	}
	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();

?>
