/**
 * 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 { Base } from "../types/base.mjs";
import { getGlobalObject } from "../types/global.mjs";
import { validateString } from "../types/validate.mjs";
import { ATTRIBUTE_THEME_NAME, DEFAULT_THEME } from "./constants.mjs";
import { instanceSymbol } from "../constants.mjs";
export { Theme, getDocumentTheme };

/**
 * The Theme class provides the functionality for the theme.
 *
 * @externalExample ../../example/dom/theme.mjs
 * @license AGPLv3
 * @since 1.7.0
 * @copyright Volker Schukai
 * @summary A theme utility for applying and coordinating Monster theme state in the DOM.
 */
class Theme extends Base {
	/**
	 *
	 * @param name
	 * @throws {TypeError} value is not a string
	 */
	constructor(name) {
		super();
		validateString(name);
		this.name = name;
	}

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

	/**
	 *
	 * @return {string}
	 */
	getName() {
		return this.name;
	}
}

/**
 * The theming used in the document can be defined via the html-tag.
 * The theming is specified via the attribute `data-monster-theme-name`.
 *
 * As name for a theme all characters are valid, which are also allowed for a HTMLElement-ID.
 *
 * ```
 * <html data-monster-theme-name="my-theme">
 * ```
 *
 * the default theme name is `monster`.
 *
 * @return {Theme}
 * @license AGPLv3
 * @since 1.7.0
 */
function getDocumentTheme() {
	const document = getGlobalObject("document");
	let name = DEFAULT_THEME;

	const element = document.querySelector("html");
	if (element instanceof HTMLElement) {
		const theme = element.getAttribute(ATTRIBUTE_THEME_NAME);
		if (theme) {
			name = theme;
		}
	}

	return new Theme(name);
}
