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

const FormattedPrice = props => {
    let formattedPrice = Math.abs(props.price);
    let sign = props.price < 0 ? '-' : '';

    if (props.languageSettings) {
        formattedPrice = formattedPrice.toFixed(props.languageSettings.pricedecimals);
        formattedPrice = String(formattedPrice);

        let parts = formattedPrice.split('.');

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

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

        if (props.channelSettings !== undefined && props.channelSettings.currencySymbol !== undefined) {
            if (props.languageSettings.currencysymbolposition === 'right') {
                formattedPrice = sign + formattedPrice + ' ' + props.channelSettings.currencySymbol;
            } else {
                formattedPrice = sign + props.channelSettings.currencySymbol + formattedPrice;
            }
        }
    }

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

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

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

FormattedPrice.propTypes = {
    languageSettings: PropTypes.object,
    channelSettings: PropTypes.object,
    price: PropTypes.number,
};

export default FormattedPrice;
