import { enUS, es } from 'date-fns/locale';
import i18next from 'i18next';
import lngDetector from 'i18next-browser-languagedetector';
import { readable, writable } from './store';
const supportedDateLocales = {
    'en-US': enUS,
    'es-ES': es,
};
export function loadTranslations(translations) {
    for (const language in translations) {
        i18next.addResourceBundle(language, 'translation', translations[language]);
    }
}
i18next.use(lngDetector).init({
    fallbackLng: 'en',
    joinArrays: '\n',
});
i18next.on('languageChanged', lng => {
    const locale = getDateLocale(lng);
    dateOptions = { locale };
    locales.set(Object.keys(i18next.services.resourceStore.data));
});
function getDateLocale(lng) {
    return supportedDateLocales[lng] || (lng && supportedDateLocales[lng.split('-')[0]]);
}
export let dateOptions = { locale: getDateLocale(i18next.language) };
export const locales = writable(Object.keys(i18next.services.resourceStore.data));
export const locale = (function () {
    const { get, set, subscribe } = writable(i18next.language);
    i18next.on('languageChanged', set);
    return {
        get,
        set: promisifyCallback(i18next.changeLanguage, i18next),
        subscribe,
    };
})();
export const t = readable(i18next.t.bind(i18next), set => {
    i18next.on('languageChanged', () => set(i18next.t.bind(i18next)));
});
export const escapedT = function (str, params) {
    if (typeof params !== 'string')
        params.interpolation = { escapeValue: true };
    return i18next.t(str, params);
};
export function promisifyCallback(fn, thisArg) {
    return function (...args) {
        return new Promise((resolve, reject) => {
            args.push((err, result) => (err ? reject(err) : resolve(result)));
            fn.apply(thisArg, args);
        });
    };
}
