import buildString from '@connect/string-placeholders';
import common from './common';

const DatePattern = {
    default: '${d}\u00a0${M} ${y}\u00a0года',
    date_time: '${d}\u00a0${M} ${y}\u00a0года в ${h}:${mm}',
    short: '${d}\u00a0${M}',
    time: '${hh}:${mm}',
};

const PLURALIZATION_PATTERN = '${number}\u00a0${objects}';

const NUMBER_FORMAT = {
    digitGroup: { size: 3, delimiter: '\u00a0' },
    fraction: { delimiter: ',' },
};

const CURRENCY_PATTERNS = {
    RUB: '${amount}\u00a0\u20bd',
    USD: '$\u2009${amount}',
};

const MONTHS = [
    'января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
    'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря',
];

// 12345.6789 > '12 345,6789'
function formatNumber(value, type) {
    return common.formatNumber(value, NUMBER_FORMAT, type);
}

// forms: [ one, few, many ]
function pluralize(number, forms, pattern) {
    const formattedNumber = formatNumber(number);
    const unsignedNumber = Math.abs(number);

    if (!(forms instanceof Array)) {
        return buildString(pattern || PLURALIZATION_PATTERN, {
            number: formattedNumber, objects: forms,
        });
    }

    let index = 2;

    if (unsignedNumber % 10 === 1 && unsignedNumber % 100 !== 11) {
        index = 0;
    } else if (unsignedNumber % 10 >= 2 && unsignedNumber % 10 <= 4 &&
        (unsignedNumber % 100 < 10 || unsignedNumber % 100 >= 20)) {
        index = 1;
    }

    return buildString(pattern || PLURALIZATION_PATTERN, {
        number: formattedNumber, objects: forms[index],
    });
}

function formatCurrency(amount, currency) {
    if (!CURRENCY_PATTERNS[currency]) {
        return `${formatNumber(amount, 'currency')}\u00a0${currency}`;
    }

    return buildString(CURRENCY_PATTERNS[currency], {
        amount: formatNumber(amount, 'currency'),
    });
}

function formatDate(date, format = 'default') {
    const d = date instanceof Date ? date : new Date(date);

    return buildString(DatePattern[format] || DatePattern.default, {
        d: d.getDate(),
        M: MONTHS[d.getMonth()],
        y: d.getFullYear(),
        h: d.getHours(),
        hh: common.pad(d.getHours(), 2),
        mm: common.pad(d.getMinutes(), 2),
        ss: common.pad(d.getSeconds(), 2),
    });
}

const ru = {
    pluralize,
    formatNumber,
    formatCurrency,
    formatDate,
};

export default ru;
