/*!
 * React Native Globalize
 *
 * Copyright 2015-2020 Josh Swan
 * Released under the MIT license
 * https://github.com/joshswan/react-native-globalize/blob/master/LICENSE
 */
import Cldr from 'cldrjs';
import dayjs from 'dayjs';
export function getLocaleId(locale) {
    // iOS returns system locale info with underscores
    return locale.replace(/_/g, '-');
}
export function getAvailableLocales() {
    var _a;
    return Object.keys(((_a = Cldr._raw) === null || _a === void 0 ? void 0 : _a.main) || {});
}
export function localeIsLoaded(locale) {
    var _a, _b;
    return !!((_b = (_a = Cldr._raw) === null || _a === void 0 ? void 0 : _a.main) === null || _b === void 0 ? void 0 : _b[getLocaleId(locale)]);
}
export function findFallbackLocale(locale) {
    const locales = getAvailableLocales();
    for (let i = locale.length - 1; i > 1; i -= 1) {
        const key = locale.substring(0, i);
        if (locales.includes(key)) {
            return key;
        }
    }
    return null;
}
export function getCurrencySymbol(locale, currencyCode, altNarrow = false) {
    var _a;
    // Check whether the locale has been loaded
    if (!locale || !localeIsLoaded(locale)) {
        return null;
    }
    const { currencies } = Cldr._raw.main[locale].numbers;
    const key = altNarrow ? 'symbol-alt-narrow' : 'symbol';
    return ((_a = currencies) === null || _a === void 0 ? void 0 : _a[currencyCode][key]) || null;
}
export function logError(message, exception) {
    if (process.env.NODE_ENV !== 'production') {
        // eslint-disable-next-line no-console
        console.error(`[RNGlobalize] ${message}${exception ? `\n${exception.stack}` : ''}`);
    }
}
const UNITS = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second'];
export function selectTimeUnit(value) {
    if (value instanceof Date) {
        const date = dayjs(value);
        const now = dayjs();
        for (let i = 0, l = UNITS.length; i < l; i += 1) {
            const diff = date.diff(now, UNITS[i]);
            if (diff >= 1 || diff <= -1 || i === l - 1) {
                return [diff, UNITS[i]];
            }
        }
    }
    return [Number(value), 'second'];
}
