/**
 * Retrieves a locale string from the navigator object.
 * Checks languages, userLanguage and language
 *
 * Uses the first valid language. If the first valid language doesn't contain a country code,
 * it will search for a locale string with the same language and a country code in the remaining options.
 *
 * @returns {(string | undefined)}
 */
export const detectLocaleFromNavigator = () => {
    if (typeof navigator === "undefined") {
        return;
    }
    const candidates = new Set();
    if (navigator.languages && navigator.languages.length > 0) {
        navigator.languages.forEach(value => candidates.add(value));
    }
    if ("userLanguage" in navigator && navigator["userLanguage"]) {
        candidates.add(navigator["userLanguage"]);
    }
    if ("language" in navigator && navigator.language) {
        candidates.add(navigator.language);
    }
    const firstCandidate = candidates.values().next().value;
    if (firstCandidate.indexOf("-") > -1) {
        return firstCandidate;
    }
    // first candidate is language only -> try to find the complete locale next
    for (const locale of candidates) {
        if (locale.indexOf(firstCandidate) === 0) {
            return locale;
        }
    }
    return firstCandidate;
};
