var i18n = require('../common/i18n');

module.exports = {
    formatted_number,
    signed_formatted_number,
    sign_type,
    percentage,
    memory_units,
    split_digits
};

function signed_formatted_number(x, options) {
    return (x > 0 ? '+' : '') + formatted_number(x, options);
}

function formatted_number(x, options) {
    return i18n.getDictionary(options).formatNumber(x);
}

function sign_type(x) {
    return typeof x !== 'number' || x === 0 ? 'neutral' : (x > 0 ? 'positive' : 'negative');
}

function percentage(value, baseline) {
    if (typeof value !== 'number' || typeof baseline !== 'number') {
        return 0;
    }
    return baseline === 0 ? 0 : Math.min(Math.abs(value/baseline), 1)*100;
}

const DISK_SPACE_UNITS = [ 'B', 'KB', 'MB', 'GB', 'TB' ];

function memory_units(x, options) {
    if (typeof x !== 'number') {
        return;
    }

    if (x === 0) {
        return '0';
    }

    var k = 0, z = x;
    var dictionary = i18n.getDictionary(options);

    while ((z /= 1024) >= 1 && k++ < DISK_SPACE_UNITS.length) {
        x = z;
    }

    return x.toFixed(2) + ' ' + dictionary.pick('common.unit.' + DISK_SPACE_UNITS[k]);
}

function split_digits(x) {
    return String(x).split('').map(digit => '<span>' + digit + '</span>').join('');
}
