/**
 * 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 { internalStateSymbol } from "../../constants.mjs";
import { extend } from "../../data/extend.mjs";
import { getGlobalFunction } from "../../types/global.mjs";
import {
	ATTRIBUTE_CLASS,
	ATTRIBUTE_ID,
	ATTRIBUTE_SRC,
	ATTRIBUTE_TITLE,
	ATTRIBUTE_TYPE,
	TAG_SCRIPT,
} from "../constants.mjs";
import {
	KEY_DOCUMENT,
	KEY_QUERY,
	referenceSymbol,
	Resource,
} from "../resource.mjs";
import { instanceSymbol } from "../../constants.mjs";

export { Data };

const KEY_ALLOWED_ORIGINS = "allowedOrigins";
const JSON_SCRIPT_TYPE_PATTERN =
	/^(application\/json|text\/json|application\/[a-z0-9.+-]+\+json)$/i;

/**
 * This class is used by the resource manager to embed data.
 *
 * @license AGPLv3
 * @since 1.25.0
 * @copyright Volker Schukai
 * @summary A Data Resource class
 */
class Data extends Resource {
	/**
	 * @property {string} mode=cors https://developer.mozilla.org/en-US/docs/Web/API/fetch
	 * @property {string} credentials=same-origin https://developer.mozilla.org/en-US/docs/Web/API/fetch
	 * @property {string} type=application/json {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-type}
	 */
	get defaults() {
		return extend({}, super.defaults, {
			mode: "cors",
			credentials: "same-origin",
			type: "application/json",
			[KEY_ALLOWED_ORIGINS]: ["self"],
		});
	}

	/**
	 *
	 * @return {Monster.DOM.Resource.Data}
	 */
	create() {
		createElement.call(this);
		return this;
	}

	/**
	 * This method appends the HTMLElement to the specified document
	 *
	 * throws {Error} target not found
	 * @return {Monster.DOM.Resource}
	 */
	connect() {
		if (!(this[referenceSymbol] instanceof HTMLElement)) {
			this.create();
		}

		appendToDocument.call(this);
		return this;
	}

	/**
	 * This method is called by the `instanceof` operator.
	 * @return {symbol}
	 * @since 2.1.0
	 */
	static get [instanceSymbol]() {
		return Symbol.for("@schukai/monster/dom/resource/data");
	}

	/**
	 * @return {string}
	 */
	static getURLAttribute() {
		return ATTRIBUTE_SRC;
	}
}

/**
 * @private
 * @return {Monster.DOM.Resource.Data}
 */
function createElement() {
	const document = this.getOption(KEY_DOCUMENT);
	const type = this.getOption(ATTRIBUTE_TYPE);

	if (!isInertJSONType(type)) {
		throw new Error("unsupported data resource type");
	}

	this[referenceSymbol] = document.createElement(TAG_SCRIPT);

	for (const key of [
		ATTRIBUTE_TYPE,
		ATTRIBUTE_ID,
		ATTRIBUTE_CLASS,
		ATTRIBUTE_TITLE,
	]) {
		if (this.getOption(key) !== undefined) {
			this[referenceSymbol][key] = this.getOption(key);
		}
	}

	return this;
}

/**
 * @private
 * @return {Promise}
 * throws {Error} target not found
 */
function appendToDocument() {
	const document = this.getOption(KEY_DOCUMENT);
	const url = getValidatedURL.call(this, document);
	const targetNode = document.querySelector(this.getOption(KEY_QUERY, "head"));
	if (!(targetNode instanceof HTMLElement)) {
		throw new Error("target not found");
	}

	targetNode.appendChild(this[referenceSymbol]);

	getGlobalFunction("fetch")(url.toString(), {
		method: "GET", // *GET, POST, PUT, DELETE, etc.
		mode: this.getOption("mode", "cors"), // no-cors, *cors, same-origin
		cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
		credentials: this.getOption("credentials", "same-origin"), // include, *same-origin, omit
		headers: {
			Accept: this.getOption("type", "application/json"),
		},
		redirect: "follow", // manual, *follow, error
		referrerPolicy: "no-referrer", // no-referrer,
	})
		.then((response) => {
			return response.text();
		})
		.then((text) => {
			const textNode = document.createTextNode(text);
			this[referenceSymbol].appendChild(textNode);

			this[internalStateSymbol].getSubject()["loaded"] = true;
		})
		.catch((e) => {
			this[internalStateSymbol].setSubject({
				loaded: true,
				error: e.toString(),
			});
		});

	return this;
}

/**
 * @private
 * @param {string} type
 * @return {boolean}
 */
function isInertJSONType(type) {
	if (type === undefined) {
		return false;
	}

	return JSON_SCRIPT_TYPE_PATTERN.test(String(type).split(";")[0].trim());
}

/**
 * @private
 * @param {Document} document
 * @return {URL}
 */
function getValidatedURL(document) {
	const url = new URL(this.getOption(ATTRIBUTE_SRC), document.baseURI);

	if (!["http:", "https:"].includes(url.protocol)) {
		throw new Error("unsupported data resource protocol");
	}

	const allowedOriginsOption = this.getOption(KEY_ALLOWED_ORIGINS, ["self"]);
	const allowedOrigins = Array.isArray(allowedOriginsOption)
		? allowedOriginsOption
		: [allowedOriginsOption];
	const documentOrigin = new URL(document.baseURI).origin;
	const allowed = allowedOrigins.map((origin) =>
		origin === "self"
			? documentOrigin
			: new URL(origin, document.baseURI).origin,
	);

	if (!allowed.includes(url.origin)) {
		throw new Error("data resource origin not allowed");
	}

	return url;
}
