/*************************************************************************************************************
This file contains mysql connect functions
2012/6 by Dlxko
**************************************************************************************************************/
#include "Mysql.h"

// Local statics
static MYSQL_RES * result;
static int rows;
static string arguments;

/****** Return integer result of Mysql execution *****/
int function_mysql_returned(char * argument)
{
	// Get arguments
	arguments = argument;

	// Mysql init
	if (mysql_init(&mySQL))
	{
		// Server connect
		if (mysql_real_connect(&mySQL, DB_IP, DB_USER, DB_PASS, DB_NAME, DB_PORT, 0, 0))
		{
			// Execute arguments
			if (mysql_real_query(&mySQL,arguments.c_str(),arguments.length()) == 0)
			{
				if (mysql_store_result(&mySQL))
				{
					rows = (int)(mysql_affected_rows(&mySQL));
					if (rows > 0)
					{
						mysql_close(&mySQL);
						return MORE_ROWS_OR_SEARCHED;
					}
					else
					{
						mysql_close(&mySQL);
						return NO_ROWS_OR_NOTSEARCHED;
					}
				}
				else
				{
					mysql_close(&mySQL);
					return NO_RESULT_OR_SUCESS;
				}
			}
			else
			{
				mysql_close(&mySQL);
				return NOT_EXECUTET_QUERY;
			}
		}
		else
		{
			std::cout << color(FOREGROUND_RED|FOREGROUND_BLUE) << "|ERR|->>"
				<< color(FOREGROUND_RED|FOREGROUND_RED) << "Couldn't connect to database !!!"
				<< std::endl;
		}
	}
	else
	{
		std::cout << color(FOREGROUND_RED|FOREGROUND_BLUE) << "|ERR|->>"
			<< color(FOREGROUND_RED|FOREGROUND_RED) << "Couldn't init MySQL !!!"
			<< std::endl;
	}

	mysql_close(&mySQL);
	return 4;
}

/****** Return result of Mysql execution *****/
MYSQL_RES *function_mysql_result(char * argument)
{
	// Get arguments
	arguments = argument;

	// Mysql init
	if (mysql_init(&mySQL))
	{
		// Server connect
		if (mysql_real_connect(&mySQL, DB_IP, DB_USER, DB_PASS, DB_NAME, DB_PORT, 0, 0))
		{
			// Execute arguments
			if (mysql_real_query(&mySQL,arguments.c_str(),arguments.length()) == 0)
			{
				// Save result
				result = mysql_store_result(&mySQL);
			}
		}
		else
		{
			std::cout << color(FOREGROUND_RED|FOREGROUND_BLUE) << "|ERR|->>"
				<< color(FOREGROUND_RED|FOREGROUND_RED) << "Couldn't connect to database !!!"
				<< std::endl;
		}
	}
	else
	{
		std::cout << color(FOREGROUND_RED|FOREGROUND_BLUE) << "|ERR|->>"
			<< color(FOREGROUND_RED|FOREGROUND_RED) << "Couldn't init MySQL !!!"
			<< std::endl;
	}

	mysql_close(&mySQL);
	return result;
}