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

namespace SiWeather\Webservice;

/**
  * @brief Configures the Webservice and creates all needed files and directories (e.g. Databases)
  *
  * @note Requires php-posix!
  */
class Setup {

	public function __construct(){
		$this->_webserviceConfig = new WebserviceConfig();
		$this->_dataDirectory = $this->_webserviceConfig->getConfig("dataDirectory");
		$this->_databaseHandler = new DatabaseHandler();
		$this->_databaseFile = $this->_databaseHandler->databaseFile();
		$this->_databaseDirectory = pathinfo($this->_databaseFile, PATHINFO_DIRNAME);
	}
	
	/**
	  * @brief Checks if data directory is present and writable  and returns a value from DatabaesChecks
	  *
	  * If an error occurs, the error message is stored into @p $errorMessage.
	  *
	  * @see DataDirectoryChecks
	  * @see dataDirectoryCreate()
	  */
	public function dataDirectoryCheck(&$errorMessage){
		if(!is_object($this->_webserviceConfig)){
			$errorMessage = "Could not load the webservice configuration";
			return DataDirectoryChecks::NoConfiguration;
		}
		if(!$this->_dataDirectory || empty($this->_dataDirectory)){
			$errorMessage = "Could not determine dataDirectory setting";
			return DataDirectoryChecks::NoDirectoryPath;
		}
		if(!is_dir($this->_dataDirectory)){
			$errorMessage = "Data directory does not exists";
			return DataDirectoryChecks::NotExist;
		}
		if(!is_writable($this->_dataDirectory)){
			$errorMessage = "Data directory is not writable for ". $this->getProcessUser() .":". $this->getProcessGroup() ." (". $this->_dataDirectory .")";
			return DataDirectoryChecks::NotWritable;
		}
		return DataDirectoryChecks::Success;
	}
	
	/**
	  * @brief Creates the data directory and returns a value from DatabaesChecks
	  *
	  * If an error occurs, the error message is stored into @p $errorMessage.
	  *
	  * @see DataDirectoryChecks
	  * @see dataDirectoryCreate()
	  */
	public function dataDirectoryCreate(&$errorMessage){
		$result = $this->dataDirectoryCheck($errorMessage);
		if($result == DataDirectoryChecks::Success){
			return DataDirectoryChecks::Success;
		}
		if($result == DataDirectoryChecks::NoConfiguration || $result == DataDirectoryChecks::NoDirectoryPath || $result == DataDirectoryChecks::DirectoryNotWritable){
			return $result;
		}
		if(!mkdir($this->_dataDirectory)){
			$errorMessage = "Could not create data directory (". $this->_dataDirectory .")";
			return DataDirectoryChecks::Error;
		}
		return DataDirectoryChecks::Success;
	}
	
	/**
	  * @brief Checks everything related to the database path and returns a value from DatabaesChecks
	  *
	  * If an error occurs, the error message is stored into @p $errorMessage.
	  *
	  * @see DatabaseDirectoryChecks
	  * @see databaseDirectoryCreate()
	  */
	public function databaseDirectoryCheck(&$errorMessage){
		if(is_null($this->_databaseDirectory) || empty($this->_databaseDirectory)){
			$errorMessage = "Failed to extract directory from database file path ("+ $this->_databaseFile +")";
			return DatabaseChecks::NoDirectoryPath;
		}
		if(!is_dir($this->_databaseDirectory)){
			$errorMessage = "Database directory does not exists (". $this->_databaseDirectory .")";
			return DatabaseChecks::DirectoryDoesNotExist;
		}
		if(!is_writable($this->_databaseDirectory)){
			$errorMessage = "Database directory is not writable  for ". $this->getProcessUser() .":". $this->getProcessGroup() ." (". $this->_databaseDirectory .")";
			return DatabaseChecks::DirectoryNotWritable;
		}
		return DatabaseChecks::Success;
	}
	
	/**
	  * @brief Creates the database directory  and returns a value from DatabaesChecks
	  *
	  * If an error occurs, the error message is stored into @p $errorMessage.
	  *
	  * @see DatabaseDirectoryChecks
	  * @see databaseDirectoryCheck()
	  */
	public function databaseDirectoryCreate(&$errorMessage){
		$result = $this->databaseDirectoryChecks($errorMessage);
		if($result == DatabaseChecks::Success){
			return DatabaseChecks::Success;
		}
		if($result == DatabaseChecks::NoDatabaseFile || $result == DatabaseChecks::NoDirectoryPath || $result == DatabaseChecks::DirectoryNotWritable){
			return $result;
		}
		if(!mkdir($this->_databaseDirectory)){
			$errorMessage = "Could not create database directory (". $this->_databaseDirectory .")";
			return DatabaseChecks::Error;
		}
		return DatabaseChecks::Success;
	}
	
	/**
	  * @brief Checks, if the database file is given and is in a writable path
	  *
	  * The database file itself is created by the DatabaseHandler. Therefore
	  * this function only checks, if the database directory exists, and it must be
	  * writable.
	  *
	  * @see DatabaseChecks
	  * @see databaseDirectoryCheck()
	  */
	public function databaseFileCheck(&$errorMessage){
		if(is_null($this->_databaseFile) || empty($this->_databaseFile)){
			$errorMessage = "No database file given (". $this->_databaseHandler->lastErrorMessage() .")";
			return DatabaseChecks::NoDatabaseFile;
		}
		if(file_exists($this->_databaseFile)){
			if(!is_writable($this->_databaseFile)){
				$errorMessage = "Database file is not writable for ". $this->getProcessUser() .":". $this->getProcessGroup() ." (". $this->_databaseFile .")";
				return DatabaseChecks::DatabaseFileNotWritable;
			}
			return DatabaseChecks::Success;
		}
		// if the databaseDirectoryCheck function return something other than success,
		// we probably have a problem (like no write permission, ...)
		if($this->databaseDirectoryCheck($errorMessage) != DatabaseChecks::Success){
			return DatabaseChecks::Error;
		}
		return DatabaseChecks::Success;
	}

	public function databaseConnection(&$errorMessage){
		if(!is_object($this->_databaseHandler)){
			$errorMessage = "No database handler";
			return false;
		}
		if(!$this->_databaseHandler->connect()){
			$errorMessage = "Could not connect to the database (". $db->lastErrorMessage() .")";
			return false;
		}
		
		// prepare Spatalite
		if(!$this->_databaseHandler->exec("BEGIN")){
			$errorMessage = "Could not start transaction to init Spatialite";
			return false;
		}
		if(!$this->_databaseHandler->exec("SELECT InitSpatialMetadata()")){
			$errorMessage = "Could not initiate Spatialite metadata";
			return false;
		}
		if(!$this->_databaseHandler->exec("COMMIT")){
			$errorMessage = "Could not commit transaction to init Spatialite";
			return false;
		}
		
		return true;
	}
	
	public function databaseVersionSqlite(&$errorMessage){
		if(!is_object($this->_databaseHandler)){
			return 0;
		}
		$result =  $this->_databaseHandler->versionSqlite();
		if($result == 0){
			$errorMessage = $this->_databaseHandler->lastErrorMessage();
		}
		return $result;
	}
	
	public function databaseVersionSpatalite(&$errorMessage){
		if(!is_object($this->_databaseHandler)){
			return 0;
		}
		$result = $this->_databaseHandler->versionSpatialite();
		if($result == 0){
			$errorMessage = $this->_databaseHandler->lastErrorMessage();
		}
		return $result;
	}
	
	public function apiCheckWithoutRewrite(&$errorMessage){
		return $this->apiCheck("index.php/stations", $errorMessage);
	}
	
	public function apiCheckWithRewrite(&$errorMessage){
		$apiVersion = $this->_webserviceConfig->getConfig("webserviceApiVersion");
		if(!$apiVersion || empty($apiVersion)){
			$errorMessage = "Could not determine API version";
			return false;
		}
		
		return $this->apiCheck($apiVersion ."/stations", $errorMessage);
	}

	private function getProcessUser(){
		$processUser = posix_getpwuid(posix_getuid());
		return $processUser["name"];
	}
	
	private function getProcessGroup(){
		$processGroup = posix_getgrgid(posix_getgid());
		return $processGroup["name"];
	}
	
	private function apiCheck($url, &$errorMessage){
		$baseUrl = $this->_webserviceConfig->getConfig("webserviceBaseUrl");
		if(!$baseUrl || empty($baseUrl)){
			$errorMessage = "No webservice base url given!";
			return false;
		}

		$client = new \GuzzleHttp\Client
		(
			[
				"base_uri" => $baseUrl,
				"timeout" => 2.0,
				"http_errors" => false,
			]
		);
		$response = $client->get($url);
		if(is_null($response)){
			$errorMessage = "Webservice has not answered at url ". $baseUrl ."!";
			return false;
		}
		$result = $response->getStatusCode();
		if($result != 200){
			$errorMessage = "Got http error ". $result ." (". $response->getReasonPhrase() .")";
			return false;
		}
		$result = $response->getReasonPhrase();
		if($result != "OK"){
			$errorMessage = "Got a http error reason with http code 200: ". $result;
			return false;
		}

		$body = $response->getBody();
		if(empty($body)){
			$errorMessage = "Got empty return value";
			return false;
		}
		
		$json = json_decode($body);
		if(is_null($json)){
			$errorMessage = "Could not decode json message body";
			return false;
		}
		return true;
	}

	private $_webserviceConfig;
	private $_dataDirectory;
	private $_databaseHandler;
	private $_databaseFile;
}

?>
