import { GET as langs } from '../../pages/api/lang.json';

export async function getSupportedLanguages() {
    return await (await langs()).json() as { id: string, name: string }[]
}

export async function getHighestWeightedLanguage(header: string | null): Promise<any> {
    if(header === null) return 'en';
    const supportedLanguages = await getSupportedLanguages();

    const langs = header.split(',');
    let highestWeight = 0;
    let highestWeightedLang = 'en';

    for(const lang of langs) {
        const subArray = lang.split(";");
        const langName = subArray[0];
        const langWeight = subArray.filter((sub: string) => sub.includes("q=")).length > 0 ? parseFloat(subArray.filter((sub: string) => sub.includes("q="))[0].split("=")[1]) : 1;

        if(langWeight > highestWeight && supportedLanguages.find(l => l.id === langName)) {
            highestWeight = langWeight;
            highestWeightedLang = langName;
        }
    }
    
    return highestWeightedLang;
}

export async function getLocales(language: string) {
    if(!(await getSupportedLanguages()).find(l => l.id === language)) {
        console.log(await getSupportedLanguages(), language)
        return null;
    }

    const lang = await (await fetch(`https://localhost:4321/api/lang/${language}.json`)).json();

    return lang.data;
}

export function getName(locale: { [key: string]: { id: string, name: string }[] }, type: string, name: string) {
    return locale[type].find((element: { id: string }) => element.id === name)?.name ?? `NTL_${name}`;
}

export function getObj(locale: { [key: string]: { id: string, name: string, description: string | null }[] }, type: string, name: string) {
    return locale[type].find((element: { id: string }) => element.id === name) ?? { id: name, name: `NTL_${name}`, description: `NTL_${name}` };
}