import find from 'lodash/find';
import get from 'lodash/get';
import map from 'lodash/map';

function getCookieValue(key: string) {
    const cookies = map(document.cookie.split(';'), (c) => c.split('='));
    return get(find(cookies, (c) => c[0].trim() === key.trim()), '[1]', '');
}

function getRhLocaleLang() {
    const cookieLang = getCookieValue('rh_locale') || 'en_US';
    return cookieLang.split('_')[0];
}

const resources = {
    de: {
        translation: {}
    },
    es: {
        translation: {}
    },
    fr: {
        translation: {}
    },
    it: {
        translation: {}
    },
    ja: {
        translation: {}
    },
    ko: {
        translation: {}
    },
    pt: {
        translation: {}
    },
    zh: {
        translation: {}
    },
    ru: {
        translation: {}
    }
};

export async function initializeTranslations() {
    const lang = getRhLocaleLang();
    if (lang !== 'en') {
        let output = null;
        switch (lang) {
            case 'de':
                output = await import(/* webpackChunkName: "de" */ `${'../template-de.po'}`);
                break;
            case 'es':
                output = await import(/* webpackChunkName: "es" */ `${'../template-es.po'}`);
                break;
            case 'fr':
                output = await import(/* webpackChunkName: "fr" */ `${'../template-fr.po'}`);
                break;
            case 'it':
                output = await import(/* webpackChunkName: "it" */ `${'../template-it.po'}`);
                break;
            case 'jp':
                output = await import(/* webpackChunkName: "jp" */ `${'../template-jp.po'}`);
                break;
            case 'ko':
                output = await import(/* webpackChunkName: "ko" */ `${'../template-ko.po'}`);
                break;
            case 'pt':
                output = await import(/* webpackChunkName: "pt" */ `${'../template-pt.po'}`);
                break;
            case 'zh':
                output = await import(/* webpackChunkName: "zh" */ `${'../template-zh.po'}`);
                break;
            case 'ru':
                output = await import(/* webpackChunkName: "ru" */ `${'../template-ru.po'}`);
                break;
        }
        if (output) {
            resources[lang].translation = output;
        }
        return {translation: resources, lang};
    }
}
