/**
 * 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 { parseLocale } from "../i18n/locale.mjs";
import { getDocument } from "./util.mjs";
import { getGlobalObject } from "../types/global.mjs";

export { getLocaleOfDocument };

/**
 * @private
 * @type {string}
 */
const DEFAULT_LANGUAGE = "en";

/**
 * With this function, you can read the language version set by the document.
 * For this, the attribute `lang` in the HTML tag is read. If no attribute is set, `en` is used as default.
 * Alternatively, the language version of the browser is used.
 *
 * ```html
 * <html lang="en">
 * ```
 *
 * You can call the function via `getLocaleOfDocument()`.
 *
 * @license AGPLv3
 * @since 1.13.0
 * @copyright Volker Schukai
 * @throws {TypeError} value is not a string
 * @throws {Error} unsupported locale
 * @summary Tries to determine the locale used
 * @return {Locale}
 */
function getLocaleOfDocument() {
	const document = getDocument();

	const html = document.querySelector("html");
	if (html instanceof HTMLElement && html.hasAttribute("lang")) {
		const locale = html.getAttribute("lang");
		if (locale) {
			return new parseLocale(locale);
		}
	}

	const navigatorLanguage = getNavigatorLanguage();
	if (navigatorLanguage) {
		return parseLocale(navigatorLanguage);
	}

	return parseLocale(DEFAULT_LANGUAGE);
}

/**
 * @private
 * @return {string|undefined|*}
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages
 */
const getNavigatorLanguage = () => {
	const navigator = getGlobalObject("navigator");
	if (navigator === undefined) {
		return undefined;
	}

	if (navigator.hasOwnProperty("language")) {
		const language = navigator.language;
		if (typeof language === "string" && language.length > 0) {
			return language;
		}
	}

	const languages = navigator?.languages;
	if (Array.isArray(languages) && languages.length > 0) {
		return languages[0];
	}

	return undefined;
};
