#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#endif	//	_WIN32

#include "uuid.h"
#include <stdio.h>
#include <string.h>

DEFINE_UUID(UUID_NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

int _uuid_parse(const char *pszIn, uuid_t *uuid)
{
	int i, nRet = 0;

	if(pszIn && uuid && strlen(pszIn) == _UUID_STRING_LEN)
	{
		int n[8];

		nRet = sscanf(pszIn,
				"%08x-%04hx-%04hx-%02x%02x-%02x%02x%02x%02x%02x%02x",
				&uuid->Data1,
				&uuid->Data2,
				&uuid->Data3,
				&n[0], &n[1],
				&n[2], &n[3], &n[4], &n[5], &n[6], &n[7]);

		if(nRet == 11)
		{
			for(i = 0; i < 8; i++)
			{
				uuid->Data4[i] = (unsigned char)n[i];
			}
		}
	}

	return nRet == 11;
}

int _uuid_unparse(const uuid_t *uuid, char *pszOut, size_t nCChOut)
{
	if(!uuid || !pszOut || nCChOut <= _UUID_STRING_LEN)
		return 0;

	return sprintf(pszOut, "%08x-%04hx-%04hx-%02hx%02hx-%02hx%02hx%02hx%02hx%02hx%02hx",
				uuid->Data1,
				uuid->Data2,
				uuid->Data3,
				uuid->Data4[0], uuid->Data4[1],
				uuid->Data4[2], uuid->Data4[3], uuid->Data4[4], uuid->Data4[5], uuid->Data4[6], uuid->Data4[7]);
}

int _uuid_compare(const uuid_t *uuid1, const uuid_t *uuid2)
{
	if(uuid1 && uuid2)
		return memcmp(uuid1, uuid2, sizeof(uuid_t));
	return 0;
}

void _uuid_copy(uuid_t *uuDest, const uuid_t *uuSrc)
{
	if(uuDest && uuSrc)
		memcpy(uuDest, uuSrc, sizeof(uuid_t));
}

int _uuid_is_null(const uuid_t *uuid)
{
	return !_uuid_compare(uuid, &UUID_NULL);
}
