import _ from 'lodash';
import AuthStore from 'stores/Auth';
import template from './template';
import ru from './i18n.ru';
import en from './i18n.en';
import tr from './i18n.tr';

const Locale = { ru, en, tr };

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

function getCurrentLocale() {
    return Locale[AuthStore.getLocale()] || 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 '';
    }

    let locale = getCurrentLocale();

    if (locale.formatDate) {
        return locale.formatDate(date, format);
    }

    let { DatePattern, Months } = locale;
    let components;

    // строковая дата без учёта часового пояса
    if (typeof date === 'string' && /^\d+-\d+-\d+$/.test(date)) {
        let [y, m, d] = date.split('-').map(x => Number(x.replace(/^0/, '')));

        components = {
            date: d,
            month: Months[m - 1],
            year: y,
        };
    } else {
        let d = date instanceof Date ? date : new Date(date);

        components = {
            date: d.getDate(),
            month: Months[d.getMonth()],
            year: d.getFullYear(),
        };
    }

    return template.build(DatePattern[format] || DatePattern.default, components);
}

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 (_.find(timezones, item => item.val === timezone) || timezones[0]).text;
}
