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

const DatePattern = {
    default: '${M}\u00a0${d},\u00a0${y}',
    date_time: '${M}\u00a0${d},\u00a0${y} at ${h}:${mm}',
    short: '${M}\u00a0${d}',
    time: '${hh}:${mm}',
};

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

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

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

const MONTHS = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December',
];

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

// forms: [ one, many ]
export function pluralize(number, forms, pattern) {
    return buildString(pattern || PLURALIZATION_PATTERN, {
        number: formatNumber(number),
        objects: forms instanceof Array ? forms[Math.abs(number) === 1 ? 0 : 1] : forms,
    });
}

function formatCurrency(amount, currency) {
    if (!CURRENCY_PATTERNS[currency]) {
        return `${currency}\u00a0${formatNumber(amount, '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 en = {
    pluralize,
    formatNumber,
    formatCurrency,
    formatDate,
};

export default en;
