// vim:fileencoding=utf-8:foldmethod=marker

#include "uuid.h"
#include "../common/aliases/aliases.h"
#include "../common/assert/assert.h"
#include "../base/strings/str8/str8.h"
#include "../prng/xorshift/xorshift.h"
#include <inttypes.h>

#define UUID_STR_FORMAT ("%.8" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.12" PRIx64)

typedef struct UUID4 UUID4;
struct UUID4 {
	u64 high;
	u64 low;
};

wp_intern UUID4 generate_uuid4(void);
wp_intern void  uuid4_to_uuid(const UUID4* uuid4, WpUuid *uuid);

WpUuid *wpUuidInitUuid4(WpUuid *uuid) {
	wpDebugAssert(uuid != NULL, "`uuid` should not be NULL");

	UUID4 uuid4 = generate_uuid4();
	uuid4_to_uuid(&uuid4, uuid);

	return uuid;
}

wp_intern UUID4 generate_uuid4(void) {
	wp_persist WpXor256State state = {0};
	wp_persist b8 initialised = false;

	if (!initialised) {
		initialised = true;
		state       = wpPrngXorshiftInit();
	}

	UUID4 uuid = (UUID4){
		.high  = wpPrngXorshift256(&state),
		.low  = wpPrngXorshift256(&state),
	};

	uuid.high = (uuid.high  & 0xffffffffffff0fff) | 0x0000000000004000;
	uuid.low  = (uuid.low   & 0x3fffffffffffffff) | 0x8000000000000000;

	return uuid;
}

wp_intern void uuid4_to_uuid(const UUID4* uuid4, WpUuid *uuid) {
	u64 group1 = uuid4->high >> 32;
	u64 group2 = (uuid4->high << 32) >> 48;
	u64 group3 = (uuid4->high << 48) >> 48;
	u64 group4 = uuid4->low >> 48;
	u64 group5 = (uuid4->low << 16) >> 16;

	wpStr8Format(&(uuid->uuid), UUID_STR_FORMAT, group1, group2, group3, group4, group5);
}
