package com.sjkj.base_lib.utils;

import android.annotation.SuppressLint;
import android.text.InputFilter;
import android.text.Spanned;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("DefaultLocale")
public class DecimalDigitsInputFilter implements InputFilter {
    Pattern mPattern;

    public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
        String regex = String.format("[0-9]{0,%d}+(\\.[0-9]{0,%d})?", digitsBeforeZero, digitsAfterZero);
        mPattern = Pattern.compile(regex);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        //直接输入"."返回"0."
        //".x"删除"x"输出为"."，inputFilter无法处理成"0."，所以只处理直接输入"."的case
        if (".".contentEquals(source) && "".equals(dest.toString())) {
            return "0.";
        }
        StringBuilder builder = new StringBuilder(dest);
        if ("".contentEquals(source)) {
            builder.replace(dstart, dend, "");
        } else {
            builder.insert(dstart, source);
        }
        String resultTemp = builder.toString();
        //判断修改后的数字是否满足小数格式，不满足则返回 "",不允许修改
        Matcher matcher = mPattern.matcher(resultTemp);
        if (!matcher.matches()) {
            return "";
        }
        return null;
    }

}

