import get from 'lodash/get';
import set from 'lodash/set';
import ru from './locale.ru';
import en from './locale.en';
import tr from './locale.tr';

const Locale = { ru, en, tr };
const currentLocale = window.ya.connect.config.app.locale;

function getCurrentLocale() {
    return Locale[currentLocale] || Locale.ru;
}

/**
 * Локализация по ключу и, опционально, форматирование строки по шаблону
 * @param {String} key
 * @param {?Object|Array} [data]
 * @returns {String|undefined}
 */
export function i18n(key, data) {
    const content = get(window.ya, `connect.i18n.${key}`);

    if (typeof content === 'string' && data) {
        return content.replace(/\{([^\{\}]+)\}/g, (match, name) => data[name]);
    }

    // @if NODE_ENV='development'
    if (!content) {
        console.warn(`Не найден перевод для ключа ${key}`); // eslint-disable-line no-console
    }
    // @endif

    return content;
}

export function toHtml(s) {
    return s ? s.replace(/\\n/g, '<br/>') : '';
}

export function pluralize(number, forms, pattern) {
    return getCurrentLocale().pluralize(number, forms, pattern);
}

export function formatNumber(value) {
    return getCurrentLocale().formatNumber(value);
}

export function formatCurrency(amount, currency) {
    if (amount === undefined || amount === null || Number.isNaN(amount)) {
        return '';
    }
    const content = getCurrentLocale().formatCurrency(amount, currency);

    return `<span class="currency-amount">${content}</span>`;
}

export function formatDate(date, format) {
    if (date === null || date === undefined) {
        return '';
    }

    return getCurrentLocale().formatDate(date, format);
}

export function formatTime(date) {
    date = date instanceof Date ? date : new Date(date);

    return `${date.getHours()}:${date.getMinutes()}`;
}

export function formatDateTime(date) {
    return (
        '<span class="date-time">' +
            `<span class="date">${formatDate(date)}</span> ` +
            `<span class="time">${formatTime(date)}</span>` +
        '</span>'
    );
}

export function getTimezoneList() {
    return get(window.ya, 'connect.i18n.timezones', []);
}

export function getTimezoneDescription(timezone) {
    const timezones = getTimezoneList();

    return (timezones.find(item => item.val === timezone) || timezones[0]).text;
}

set(window.ya, 'connect.util', {
    i18n, pluralize, formatNumber, formatCurrency, formatDate,
});
