<?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();
	}

	public function connect()
	{
		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;
		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 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;
}

?>
