import NumberFormatter from 'field-kit/src/number_formatter';

class OnlyNumberFormatter extends NumberFormatter {
    constructor() {
        super();

        this.setMaximumFractionDigits(10);
    }

    // TODO: needs to handle negative numbers
    isChangeValid(change, error) {
        const pprefix = '' + this.positivePrefix();
        let numberCheck = /^\d*\.?\d*$/,
            test;

        if (pprefix.length) {
            if (change.proposed.text.indexOf(pprefix) < 0) {
                change.proposed.text = pprefix +
                    change.proposed.text;
                change.proposed.selectedRange.start += pprefix.length;
            }

            if (change.proposed.text === pprefix) {
                change.proposed.text = '';
                test = '';
            } else {
                test = change.proposed.text.slice(pprefix.length);
            }
        } else {
            test = change.proposed.text;
        }

        /* istanbul ignore if: too internal */
        if (!this._get('allowsFloats')) {
            numberCheck = /^\d*$/;
        }

        if (numberCheck.test(test)) {
            return super.isChangeValid(change, error);
        } else {
            return false;
        }
    }
}

export default OnlyNumberFormatter;
