import { isProduction, getConf, setConf } from './configuration';
import Api from '../Framework/Api';
import { use, setStore } from '../Framework/i18n';

export async function loadTranslationFile(lang, baseURL) {
    // ensure that the filename always has an underscore and no dash
    const fileKey = lang.replace('-', '_');
    const langKey = lang.substring(0, 2);

    const results = isProduction()
        ? await Promise.all([loadLanguageJson(`${baseURL}translations/frontend/${fileKey}`, langKey)])
        : await Promise.all([
              loadLanguageJson('/translations/' + fileKey + '.json', langKey),
              loadLanguageJson('/translations_custom/' + fileKey + '.json', langKey),
          ]);
    results.forEach(use);
    return results;
}

function loadLanguageJson(filename, langKey) {
    return new Promise(resolve => {
        let request = new XMLHttpRequest();

        request.open('GET', filename);
        request.addEventListener('load', () => {
            if (request.status >= 200 && request.status < 300) {
                try {
                    let obj = {};
                    obj[langKey] = JSON.parse(request.response);
                    resolve(obj);
                } catch (e) {
                    // eslint-disable-next-line no-console
                    console.warn('error parsing translations json (' + filename + '): ' + e);
                    resolve({});
                }
            } else {
                // eslint-disable-next-line no-console
                console.warn('error loading translations (' + filename + '): ' + request.statusText);
                resolve({});
            }
        });
        request.send();
    });
}

export async function findInitialLanguage() {
    const languages = (await Api.request({ url: 'languages' })).data;
    let language = languages?.find(lang => lang.isDefault)?.iso; // priority for api default language
    if (!language && languages?.length) {
        const browserLanguage = (navigator.languages?.[0] || navigator.language).replace('-', '_');
        const matchToBrowserLanguage = languages.find(lang => lang.iso === browserLanguage);
        language = (matchToBrowserLanguage || languages[0])?.iso;
    }
    return language || 'de_DE';
}

export async function initLanguage(options = {}) {
    const language = (getConf('language') || (await findInitialLanguage())).replace('_', '-');
    setConf('language', language);
    Api.setLanguage(language);
    document.documentElement.lang = language.substring(0, 2);
    const translations = await loadTranslationFile(language, getConf('network.baseURL'));
    if (options?.store) {
        setStore(options.store, language);
    }
    return {
        language,
        translations,
    };
}
