<?php

//        # Copyright (C) 2012-2013 GNU remotecontrol authors.
//        #
//        # This program is free software: you can redistribute it and/or modify
//        # it under the terms of the GNU Affero 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 Affero General Public License for more details.
//        #
//        # You should have received a copy of the GNU Affero General Public License
//        # along with this program.  If not, see <http://www.gnu.org/licenses/>.

class MySqlDataAccess
{
	// Properties
	public $Command;
	private $_connection;
	private $_connectionString;
	public $ResultSet;

	// Constructor
	public function __construct($connString)
	{
		$this->_connectionString = $connString;

		$this->CreateConnection();

		$this->Command = new MySqlCommand($this->_connection);		
	}

	// Methods
	public function Cleanup()
	{
		if($this->ResultSet)
		{
			$this->ResultSet->free();
		}

		while($this->_connection->next_result())
		{
			$temp_result = $this->_connection->store_result();

			if($temp_result)
			{
				$temp_result->free();
			}
		}

		$this->Command = new MySqlCommand();
		$this->_connection->close();
	}

	private function CreateConnection()
	{
		if(!$this->_connection)
		{
			$connStringArray = explode(';', $this->_connectionString);

			$host = '';
			$db = '';
			$user = '';
			$pwd = '';

			foreach($connStringArray as $expr)
			{
				$key = substr($expr, 0, strpos($expr, '='));
				$value = substr($expr, (strpos($expr, '=') + 1));

				switch($key)
				{
					case 'Host':

						$host = $value;

						break;

					case 'DB':

						$db = $value;

						break;

					case 'UN':

						$user = $value;

						break;

					case 'PW':

						$pwd = $value;

						break;
				}
			}

			$this->_connection = new mysqli($host, $user, $pwd, $db);
		}
	}

	public function GetData()
	{
		if($this->_connection->multi_query($this->Command->CommandText))
		{
			$this->ResultSet = $this->_connection->store_result();
		}
	}
}

?>
