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

// Local variables
static int rows = 0;

// Function to return mysql progress number
int function_mysql_returned(char * argument)
{
	// Local in-function statics
	MYSQL mySQL;
	string arguments = "";

	// Refresh
	rows = RESET;

	// Get arguments
	arguments = argument;

	// Mysql init
	if (!mysql_init(&mySQL))
	{
		function_show_error("Couldn't init MySQL !!!");
		arguments.empty();
		return 4;
	}

	// Server connect
	if (!mysql_real_connect(&mySQL, DB_IP, DB_USER, DB_PASS, DB_NAME, DB_PORT, 0, 0))
	{
		function_show_error("Couldn't connect to database !!!");
		mysql_close(&mySQL);
		arguments.empty();
		return 4;
	}

	// Execute arguments
	if (!mysql_real_query(&mySQL,arguments.c_str(),arguments.length()) == 0)
	{
		mysql_close(&mySQL);
		arguments.empty();
		return NOT_EXECUTET_QUERY;
	}

	// Try to store result
	if (!mysql_store_result(&mySQL))
	{
		mysql_close(&mySQL);
		arguments.empty();
		return NO_RESULT_OR_SUCESS;
	}

	// Get number of affected rows
	rows = (int)(mysql_affected_rows(&mySQL));
	if (rows > 0)
	{
		mysql_close(&mySQL);
		arguments.empty();
		return MORE_ROWS_OR_SEARCHED;
	}
	else
	{
		mysql_close(&mySQL);
		arguments.empty();
		return NO_ROWS_OR_NOTSEARCHED;
	}
}

// Function to return mysql result
MYSQL_RES *function_mysql_result(char * argument)
{
	// Local in-function statics
	MYSQL mySQL;
	MYSQL_RES *result = NULL;
	string arguments = "";

	// Get arguments
	arguments = argument;

	// Mysql init
	if (!mysql_init(&mySQL))
		function_show_error("Couldn't init MySQL !!!");

	// Server connect
	if (!mysql_real_connect(&mySQL, DB_IP, DB_USER, DB_PASS, DB_NAME, DB_PORT, 0, 0))
		function_show_error("Couldn't connect to database !!!");

	// Execute arguments and save result
	if (mysql_real_query(&mySQL,arguments.c_str(),arguments.length()) == 0)
		result = mysql_store_result(&mySQL);

	// Close mysql and return result
	mysql_close(&mySQL);
	arguments.empty();

	// Return it
	return result;
}