import {merge, cloneDeep} from 'lodash';

const momentLocalesMap = {
    de_DE: 'de',
    en_AU: 'en-au',
    en_US: null,
    en_GB: 'en-gb',
    en_ZZ: 'x-pseudo',
    es_419: 'es',
    es_ES: 'es',
    fr_CA: 'fr-ca',
    fr_FR: 'fr',
    it_IT: 'it',
    ja_JP: 'ja',
    pt_BR: 'pt-br',
    zh_CN: 'zh-cn',
    zh_HK: 'zh-hk',
    zh_TW: 'zh-tw'
};

function trueClone(thing) {
    return cloneDeep(merge({}, thing));
}

function setMomentLocale(moment, locale) {
    moment && moment.locale(momentLocalesMap[locale] || 'en');
}

function createStringsLoader({loader, defaultStrings, moment}) {
    const defaultStringsClone = trueClone(defaultStrings); // JS Modules cannot be cloned directly because keys are getters

    return async (locale, momentLocale = locale) => {
        let newStrings = await loader(locale);

        // loader returns null if locale is default
        if (!newStrings) {
            newStrings = defaultStringsClone;
        }

        merge(defaultStrings, defaultStringsClone, newStrings);

        setMomentLocale(moment, momentLocale);

        return defaultStrings;
    };
}

export {createStringsLoader, setMomentLocale};
