<?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 Manages the database connection for SiWeather webservice
	* @note This class needs to load the SpatialLite SQLite extension.
	*       Therefore the sqlite3.extension_dir in php.ini must be set
  *       to a path, where this extension could be found!
	*/
class DatabaseHandler {
	function __construct()
	{
		$this->_config = new WebserviceConfig();
	
		$this->_lastErrorMessage = "";
		$this->_database = null;
		if(!$this->_config->dataDirectory()){
			$this->setLastErrorMessage("Could not connect to the database: No data directory set!");
			$this->databaseFile = null;
		}
		else{
			$this->_databaseFile = $this->_config->dataDirectory() ."/siweather.sqlite";
		}
	}

	function __destruct()
	{
		if(!is_null($this->_database)){
			$this->close();
		}
	}

	public function databaseFile()
	{
		return $this->_databaseFile;
	}

	public function lastErrorMessage()
	{
		return $this->_lastErrorMessage;
	}

	public function lastDatabaseErrorMessage(){
		if(is_null($this->_database))
			return false;
		return $this->_database->lastErrorMsg();
	}

	public function lastInsertRowId(){
		if(is_null($this->_database))
			return -1;
		return $this->_database->lastInsertRowID();
	}

	/**
	 * @brief Connects to the database and does some checks.
	 *
	 * @note This function should only called by the setup with @p ignoreVersion = true!
	 *       Otherwise the database version is not checked! Data loss may be the consequence!
	 */
	public function connect($ignoreVersion = false)
	{
		if(!is_null($this->_database)){
			return true;
		}
		if(is_null($this->_databaseFile) || empty($this->_databaseFile)){
			$this->setLastErrorMessage("Could not connect to the database: No database file given");
			return false;
		}
		try {
			$db = new \SQLite3($this->_databaseFile, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
		}
		catch(\Exception $exception){
			$this->setLastErrorMessage("Could not connect to the database: "+ $exception->getMessage());
			return false;
		}
		// loading SpatiaLite as an extension
		$extension = $this->_config->getConfig("spatialiteExtension");
		if(empty($extension)){
			$this->setLastErrorMessage("No spatialiteExtension set!");
			return false;
		}
		if(!$db->loadExtension($extension)){
			$this->setLastErrorMessage("Could not load SpatialLite extension: ". $db->lastErrorMsg());
			return false;
		}
		$this->_database = $db;

		// check schema version
		if(!$this->checkVersions() && !$ignoreVersion)
			return false;
		
		return true;
	}

	public function close()
	{
		if(is_null($this->_database)){
			return true;
		}
		if($this->_database->close()){
			$this->_database = null;
			return true;
		}
		$this->setLastErrorMessage("Failed to close the database: "+ $this->_database->lastErrorMsg());
		return false;
	}
	
	public function databaseTableExists($table){
		if(!$this->_database || !is_object($this->_database)){
			return false;
		}
		$statement = $this->prepare("SELECT COUNT(*) FROM sqlite_master WHERE type=\"table\" AND name=:name");
		if(!$statement){
			$this->setLastErrorMessage(\Translator::swGettext("Could not prepare query to check if table %s exists", $table));
			return false;
		}
		$statement->bindValue(":name", $table);
		$result = $statement->execute();
		$row = $result->fetchArray();
		if(!$row || !is_array($row) || count($row) < 1 || $row[0] != 1)
			return false;
		return true;
	}
	
	public function checkVersions(){
		if(is_null($this->_database)){
			$this->setLastErrorMessage("No database available to check versions");
			return false;
		}
		$table = "schema";
		if(!$this->databaseTableExists($table)){
			$this->setLastErrorMessage("Database table with schema versions does not exists!");
			return false;
		}

		// check schema version
		$neededVersion = $this->_config->getConfig("databaseVersionCore");
		$currentVersion = $this->exec("SELECT version FROM ". $table ." WHERE name='core'");
		if(empty($neededVersion) || !is_numeric($neededVersion) || !$currentVersion || $currentVersion != $neededVersion){
			$this->setLastErrorMessage("Found wrong database core version. Expected ". $neededVersion ." got ". $currentVersion);
			return false;
		}
		return true;
	}
	
	public function exec($query)
	{
		if(is_null($this->_database)){
			return false;
		}
		if(!$this->connect()){
			return false;
		}
		$result = $this->_database->exec($query);
		if(!$result)
			$this->setLastErrorMessage("Could not execute databae query \"". $query ."\": ". $this->_database->lastErrorMsg());
		return $result;
	}
	
	public function prepare($query)
	{
		if(is_null($this->_database)){
			return false;
		}
		if(!$this->connect()){
			return false;
		}
		$result = $this->_database->prepare($query);
		if(!$result){
			error_log("logging");
			$this->setLastErrorMessage("Could not prepare database query \"". $query ."\": ". $this->_database->lastErrorMsg());
		}
		return $result;
	}
	
	public function versionSpatialite(){
		if(is_null($this->_database)){
			$this->setLastErrorMessage("No database connection");
			return 0;
		}
		if(!$this->connect()){
			return 0;
		}
		$result = $this->_database->query("SELECT spatialite_version()");
		while($row = $result->fetchArray()){
			return $row[0];
		}
		return 0;
	}
	
	public function versionSqlite(){
		if(is_null($this->_database)){
			$this->setLastErrorMessage("No database connection");
			return 0;
		}
		if(!$this->connect()){
			return 0;
		}
		$result = $this->_database->query("SELECT sqlite_version()");
 		while($row = $result->fetchArray()){
			return $row[0];
		}
		return 0;
	}

	private function setLastErrorMessage($message){
		if(!empty($message))
			error_log($message);
		$this->_lastErrorMessage = $message;
	}
	
	private $_database;
	private $_databaseFile;
	private $_lastErrorMessage;
	private $_config;
}

?>
