import FieldKit from 'field-kit';
import OnlyNumberFormatter from './only-number-formatter';

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

        this.setNumberStyle(FieldKit.NumberFormatter.Style.PERCENT)
            .setPercentSymbol('%');
    }

    isChangeValid(change, error) {
        const symbol = this.percentSymbol(),
            text = change.proposed.text;

        if (text.length && text.charAt(text.length - 1) === symbol) {
            change.proposed.text = text.slice(0, -1);
        }

        const valid = super.isChangeValid(change, error);

        if (change.proposed.text) {
            change.proposed.text += symbol;
        }

        return valid;
    }
}

export default PercentFormatter;
