import merge from 'lodash/merge';
import cloneDeep from 'lodash/cloneDeep';
import * as config from './config';

let strings;
let loader;

function setStringsLoader(l) {
    loader = l;
}

function setStrings(strs) {
    strings = strs;
}

function loadStrings(loc) {
    //TODO Catch locale load error and load default
    return new Promise(function(resolve, reject) {
        if (!loader) {
            throw new Error('Strings loader have not been configured yet, check startup sequence');
        }
        //if (!config.getConfig().userLanguage) throw new Error('Locale has not been configured');
        if (undefined !== loc) {
            config.getConfig().userLanguage = loc;
        }
        resolve(loader(config.getConfig().userLanguage));
    }).then(function(strs) {
        setStrings(strs);
        return strs;
    });
}

/**
 * @return LANG_STRINGS
 */
function getStrings() {
    if (!strings) {
        throw new Error('Strings have not been loaded yet, check startup sequence');
    }
    return strings;
}

function createStringsLoader(loader, en_US, localize) {
    const defaultStrings = cloneDeep(en_US);

    return function(locale) {
        return loader(locale).then(function(newStrings) {
            // loader returns null if locale is default
            if (!newStrings) {
                newStrings = defaultStrings;
            }

            merge(en_US, defaultStrings, newStrings);

            // Now localization strings are available and UI library can be localized
            if (localize && 'COMMON' in en_US) {
                localize(en_US.COMMON);
            }

            setStrings(en_US);

            return en_US;
        });
    };
}

export {setStringsLoader, setStrings, loadStrings, getStrings, createStringsLoader};
