/**
 * Copyright © Volker Schukai and all contributing authors, {{copyRightYear}}. All rights reserved.
 * Node module: @schukai/monster
 *
 * This source code is licensed under the GNU Affero General Public License version 3 (AGPLv3).
 * The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.en.html
 *
 * For those who do not wish to adhere to the AGPLv3, a commercial license is available.
 * Acquiring a commercial license allows you to use this software without complying with the AGPLv3 terms.
 * For more information about purchasing a commercial license, please contact Volker Schukai.
 *
 * SPDX-License-Identifier: AGPL-3.0
 */

import { internalSymbol } from "../constants.mjs";
import { random } from "../math/random.mjs";
import { isObject } from "./is.mjs";
import { Base } from "./base.mjs";
import { getGlobalObject } from "./global.mjs";

export { UUID };

/**
 * The UUID class makes it possible to get a unique UUID for an object.
 *
 * @license AGPLv3
 * @since 1.25.0
 * @copyright Volker Schukai
 * @throws {Error} unsupported
 */
class UUID extends Base {
	/**
	 *
	 */
	constructor() {
		super();

		let uuid = createWithCrypto();

		if (uuid === undefined) {
			uuid = createWithRandom();
		}

		if (uuid === undefined) {
			throw new Error("unsupported");
		}

		this[internalSymbol] = {
			value: uuid,
		};
	}

	/**
	 *
	 * @return {string}
	 */
	toString() {
		return this[internalSymbol]["value"];
	}
}

/**
 * @private
 * @return {string|undefined}
 */
function createWithRandom() {
	return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
		const r = (random(0, 65000) * 16) | 0;
		const v = c === "x" ? r : (r & 0x3) | 0x8;
		return v.toString(16)[0];
	});
}

/**
 * @private
 * @return {string|undefined}
 */
function createWithCrypto() {
	const crypt = getGlobalObject("crypto");
	if (!isObject(crypt)) return;
	if (typeof crypt?.["randomUUID"] !== "function") return;
	return crypt.randomUUID();
}
