import React from 'react';
import PropTypes from 'prop-types';

const FormattedNumber = props => {
    let formattedNumber = String(props.number);

    if (props.languageSettings) {
        let parts = formattedNumber.split('.');

        formattedNumber = addThousandsseparator(parts[0], props.languageSettings.thousandsseparator);

        if (parts[1] !== undefined) {
            formattedNumber += props.languageSettings.decimalpoint + parts[1];
        }
    }

    return <span>{formattedNumber}</span>;
};

const addThousandsseparator = (nStr, separator) => {
    nStr += '';

    let rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
        nStr = nStr.replace(rgx, '$1' + separator + '$2');
    }
    return nStr;
};

FormattedNumber.propTypes = {
    number: PropTypes.number,
    languageSettings: PropTypes.object,
};

export default FormattedNumber;
