#include "Windows.h"
#include "scripts.h"
#include "engine.h"
#include "sqlite3.h"
#include "YaRR.h"
#include "YaRR-DB.h"



/************************************** Polite Request ***************************************
** I have put a lot of time and effort into YaRR. If you want to use some of the source     **
** please tell me. Anything used from YaRR must be open source, as is scripts.dll.          **
***************************************** Thank you *****************************************/


sqlite3 *YaRRDB::db;

void YaRRDB::Startup()
{
	if(sqlite3_open("YaRR.db", &db) != 0)
	{
		return;
	}
}

void YaRRDB::Shutdown()
{
	sqlite3_close(db);
}

const char *YaRRDB::Query(YaRRDB::Row ***l, const char *Format, ...)
{
	va_list va;
	_crt_va_start(va, Format);
	char *buffer = sqlite3_vmprintf(Format, va);
	va_end(va);

	char *Error = 0;
	if(sqlite3_exec(db, buffer, Callback, (void *)l, &Error) != 0)
	{
		char *ret = YaRRFunctions::strdup2(Error);
		printf("Sqlite error: %s\n", Error);
		sqlite3_free(Error);
		sqlite3_free(buffer);
		if(l)
		{
			YaRRFunctions::DeleteList(l);
		}
		return ret;
	}
	sqlite3_free(buffer);
	return 0;
}

int YaRRDB::Callback(void *Data, int argc, char **ColumnData, char **Columns)
{
	Row ***l = (Row ***)Data;
	int Write = 0;

	if(!l || argc == 0)
	{
		return 0;
	}
	if(*l == 0)
	{
		*l = (Row **)malloc(4);
		*l = 0;
	}
	else
	{
		for(; (*l)[Write]; Write++);
		*l = (Row **)realloc((Write+2)*4);
		(*l)[Write+1] = 0;
	}

	Row *r = (Row *)malloc(sizeof(YaRRDB::Row));
	r->Columns = (const char **)malloc((argc+1)*4);
	r->Columns[argc] = 0;

	r->Data = (const char **)malloc((argc+1)*4);
	r->Data[argc] = 0;

	for(int i = 0; i < argc; i++)
	{		
		r->Columns[i] = strdup(Columns[i]);
		r->Data[i] = strdup(ColumnData[i] ? ColumnData[i] : "NULL");
	}

	(*l)[Write] = r;
	return 0;
}

void YaRRDB::DeleteResult(YaRRDB::Row **list)
{
	if(!list)
	{
		return;
	}

	for(int i = 0; list[i]; i++)
	{
		free((void *)list[i]);
	}
	free((void *)list);
}

const char *YaRRDB::GetColumnData(const char *Name, Row *r)
{
	if(!r)
	{
		return 0;
	}

	for(int i = 0; list[i]; i++)
	{
		if(_stricmp(Name, r->Columns[i]) == 0)
		{
			return r->Data[i];
		}
	}
	return "null";
}