import _ from 'lodash';

const DEFAULT_NUMBER_FORMAT = {
    digitGroup: {},
    fraction: {},
};

const common = {
    formatNumber,
};

export default common;

// 12345.6789 > '12${options.digitGroup.delimiter}345${options.fraction.delimiter}6789'
// options: { digitGroup: { size, delimiter }, fraction: { delimiter } }
function formatNumber(value, options = {}, type) {
    options = _.assign({}, DEFAULT_NUMBER_FORMAT, options, { type });

    const originalValue = Number(value);

    value = String(value);

    let sign = value.charAt(0);
    let fraction = (value.match(/[\.,](\d+)$/) || [])[1];

    if (sign === '+' || sign === '-') {
        value = value.substring(1);
    } else {
        sign = '';
    }

    if (fraction) {
        value = value.substring(0, value.length - fraction.length - 1);
    }

    if (options.type === 'currency') {
        const roundedFraction = Math.round(
            100 * (Math.abs(originalValue) - Math.floor(Math.abs(originalValue)))
        );

        fraction = roundedFraction === 0 ? '' : String(roundedFraction);
    }

    let digitGroups;

    if (options.digitGroup.size) {
        digitGroups = value.match(
            new RegExp(`(\\d+?)(?=(\\d{${options.digitGroup.size}})+(?!\\d)|$)`, 'g')
        ) || [];
    } else {
        digitGroups = [value];
    }

    return [
        sign,
        digitGroups.join(options.digitGroup.delimiter || ''),
        fraction ? (options.fraction.delimiter || '.') + fraction : '',
    ].join('');
}
