//-----------------------------------------------------------------------------
// AScript uuid module
//-----------------------------------------------------------------------------
#include <ascript.h>
#ifdef HAVE_WINDOWS_H
#include <unknwn.h>
#else
#include <uuid/uuid.h>
#endif

AScript_BeginModule(uuid)

//-----------------------------------------------------------------------------
// AScript module functions: uuid
//-----------------------------------------------------------------------------
// uuid.generate():[upper]
AScript_DeclareFunction(generate)
{
	SetMode(RSLTMODE_Normal, FLAG_None);
	SetHelp(
	"Generates a Universal Unique Identifier (UUID). In default, results are output in\n"
	"lower-case characters. Specifying :upper would generates it in upper-case characters.");
	DeclareAttr(AScript_Symbol(upper));
}

AScript_ImplementFunction(generate)
{
	bool upperFlag = args.IsSet(AScript_Symbol(upper));
	char str[64];
#ifdef HAVE_WINDOWS_H
	const char *format = upperFlag?
		"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X" :
		"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x";
	GUID guid;
	::CoCreateGuid(&guid);
	::sprintf(str, format,
		guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1],
		guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
#else
	const char *format = upperFlag?
		"%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X" :
		"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x";
	uuid_t guid;
	::uuid_generate(guid);
	::sprintf(str, format,
		guid[0], guid[1], guid[2], guid[3], guid[4], guid[5], guid[6], guid[7],
		guid[8], guid[9], guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
#endif
	return Value(env, str);
}

// Module entry
AScript_ModuleEntry()
{
	// function assignment
	AScript_AssignFunction(generate);
}

AScript_ModuleTerminate()
{
}

AScript_EndModule(uuid, uuid)

AScript_RegisterModule(uuid)
