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

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

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace GnuBoat;

require_once(__DIR__ ."/../autoloader.php");

class ServiceMap extends Service
{
	function __construct()
	{
		parent::__construct();
	}

	protected function process()
	{
		header('Content-type: application/json');

		$result["error"] = 1;
		$result["errormessage"] = "Unknown Error";

		if(!array_key_exists("mapName", $_POST)){
			$result["error"] = 1;
			$result["errormessage"] = "Please specify map name (no value)";
			echo json_encode($result);
			return;
		}
		$mapName = $_POST["mapName"];
		if(empty($mapName) || $mapName == ""){
			$result["error"] = 1;
			$result["errormessage"] = "Please specifiy map name (empty value)";
			echo json_encode($result);
			return;
		}

		$mapDirectory = __DIR__ ."/../../maps";
		if(!array_key_exists("mapFile", $_FILES)){
			$result["error"] = 1;
			$result["errormessage"] = "No map file recieved";
			echo json_encode($result);
			return;
		}
		if (!isset($_FILES['mapFile']['error']) || is_array($_FILES['mapFile']['error'])){
			$result["error"] = 1;
			$result["errormessage"] = "Invalid parameters";
			echo json_encode($result);
			return;
		}
		switch ($_FILES['mapFile']['error']) {
			case UPLOAD_ERR_OK:
				break;
			case UPLOAD_ERR_NO_FILE:
				$result["error"] = 1;
				$result["errormessage"] = "No file sent";
				echo json_encode($result);
				return;
			case UPLOAD_ERR_INI_SIZE:
			case UPLOAD_ERR_FORM_SIZE:
				$result["error"] = 1;
				$result["errormessage"] = "Exceeded filesize limit.";
				echo json_encode($result);
				return;
			default:
				$result["error"] = 1;
				$result["errormessage"] = "Unknown PHP Error";
				echo json_encode($result);
				return;
		}
		$mapFileName = $mapDirectory ."/". sha1_file($_FILES['mapFile']['tmp_name']) .".mbtiles";
		if(move_uploaded_file($_FILES['mapFile']['tmp_name'], $mapFileName)){
			if(!chmod($mapFileName, 0755)){
				$result["error"] = 1;
				$result["errormessage"] = "Could not change permissions of the map file";
			}
			else{
				// correct map metadata
				$resultRename = $this->setMapName($mapFileName, $mapName);
				if($resultRename[0] === true){
					$result["error"] = 0;
					$result["errormessage"] = "";
				}
				else{
					$result["error"] = 1;
					$result["errormessage"] = $resultRename[1];
				}
			}
		}
		else {
			$result["error"] = 1;
			$result["errormessage"] = "Could not move map in place";
		}
		echo json_encode($result);
	}
	
	private function setMapName($mbTilesFile, $mapName)
	{
		if(!is_file($mbTilesFile))
			return array(false, "setMapName - Map file not found: ". $mbTilesFile);
		if(empty($mapName) || $mapName == "")
			return array(false, "setMapName - Map name empty");
		try{
			$databaseConnection = new \PDO("sqlite:". $mbTilesFile);
			$databaseConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
			
			$columnName = "name";
			$query = $databaseConnection->prepare("UPDATE metadata SET value=:value WHERE name=:name");
			$query->bindParam(":name", $columnName);
			$query->bindParam(":value", $mapName);
			if($query->execute() !== true){
				return array(false, "setMapName - Could not update metadata");
			}
			return array(true, "");
		}
		catch(\PDOException $e){
			return array(false, "setMapName - Database error: ". $e->getMessage());
		}
	}
}

?>
