const template = require('../common/template');
const common = require('./common');

module.exports = {
    pluralize,
    formatNumber,
    formatCurrency
};

const PLURALIZATION_PATTERN = '${number}\u00a0${objects}';
const DATE_PATTERN = '${date}\u00a0${month} ${year}\u00a0года';

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

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

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

// forms: [ one, few, many ]
function pluralize(number, forms, pattern) {
    if (!pattern) pattern = PLURALIZATION_PATTERN;

    let formattedNumber = formatNumber(number);
    let unsignedNumber = Math.abs(number);

    if (!(forms instanceof Array)) {
        return template.build(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 template.build(pattern, {
        number: formattedNumber, objects: forms[index]
    });
}

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

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

    return template.build(CURRENCY_PATTERNS[currency], {
        amount: formatNumber(amount, 'currency')
    });
}
