//
// MySQLException.cpp
//
// $Id: //poco/1.3/Data/MySQL/src/SessionImpl.cpp#3 $
//
// Library: Data
// Package: MySQL
// Module:  SessionImpl
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
// 
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//


#include "Poco/Data/MySQL/SessionImpl.h"
#include "Poco/Data/MySQL/MySQLStatementImpl.h"
#include "Poco/NumberParser.h"


namespace
{
	std::string copyStripped(std::string::const_iterator from, std::string::const_iterator to)
	{
		// skip leading spaces
		while ((from != to) && isspace(*from)) from++;
		// skip trailing spaces
		while ((from != to) && isspace(*(to - 1))) to--;

		return std::string(from, to);
	}
}


namespace Poco {
namespace Data {
namespace MySQL {


SessionImpl::SessionImpl(const std::string& connectionString) : _mysql(0), _connected(false), _inTransaction(0)
{
	addProperty("insertId", 
		&SessionImpl::setInsertId, 
		&SessionImpl::getInsertId);

	std::map<std::string, std::string> options;

	// Default values
	options["host"] = "localhost";
	options["port"] = "3306";
	options["user"] = "";
	options["password"] = "";
	options["db"] = "";
	options["compress"] = "";
	options["auto-reconnect"] = "";

	//
	// Parse string
	//

	for (std::string::const_iterator start = connectionString.begin();;) 
	{
		// find next ';'
		std::string::const_iterator finish = std::find(start, connectionString.end(), ';');

		// find '='
		std::string::const_iterator middle = std::find(start, finish, '=');

		if (middle == finish)
		{
			throw MySQLException("create session: bad connection string format, can not find '='");
		}

		// Parse name and value, skip all spaces
		options[copyStripped(start, middle)] = copyStripped(middle + 1, finish);

		if (finish == connectionString.end())
		{
			// end of parse
			break;
		}

		// move start position after ';'
		start = finish + 1;
	} 

	//
	// Checking
	//

	if (options["user"] == "")
	{
		throw MySQLException("create session: specify user name");
	}

	if (options["db"] == "")
	{
		throw MySQLException("create session: specify database");
	}

	unsigned int port = 0;
	if (!NumberParser::tryParseUnsigned(options["port"], port) || 0 == port || port > 65535)
	{
		throw MySQLException("create session: specify correct port (numeric in decimal notation)");
	}

	//
	// Options
	//

	if (options["compress"] == "true")
	{
		_mysql.options(MYSQL_OPT_COMPRESS);
	}
	else if (options["compress"] == "false")
	{
		// do nothing
	}
	else if (options["compress"] != "")
	{
		throw MySQLException("create session: specify correct compress option (true or false) or skip it");
	}

	if (options["auto-reconnect"] == "true")
	{
		_mysql.options(MYSQL_OPT_RECONNECT, true);
	}
	else if (options["auto-reconnect"] == "false")
	{
		_mysql.options(MYSQL_OPT_RECONNECT, false);
	}
	else if (options["auto-reconnect"] != "")
	{
		throw MySQLException("create session: specify correct auto-reconnect option (true or false) or skip it");
	}

	//
	// Real connect
	//

	_mysql.connect(
			options["host"].c_str(), 
			options["user"].c_str(), 
			options["password"].c_str(), 
			options["db"].c_str(), 
			port);

	_connected = true;
}
	

SessionImpl::~SessionImpl()
{
	close();
}
	

Poco::Data::StatementImpl* SessionImpl::createStatementImpl()
{
	return new MySQLStatementImpl(_mysql);
}	


void SessionImpl::begin()
{
	_mysql.query("START TRANSACTION");
	_inTransaction++;
}


void SessionImpl::commit()
{
	_mysql.query("COMMIT");
	_inTransaction--;

	// ?
	// mysql_commit(fMysql);
}
	

void SessionImpl::rollback()
{
	_mysql.query("ROLLBACK");
	_inTransaction--;

	// ?
	// mysql_commit(fMysql);
}
	

void SessionImpl::close()
{
	if (_connected)
	{
		_mysql.close();
		_connected = false;
	}
}
	

bool SessionImpl::isConnected()
{
	return _connected;
}
	

bool SessionImpl::isTransaction()
{
	return (_inTransaction > 0);
}


} } } // namespace Poco::Data::MySQL
