package com.zztrapp.zztrapp.widget;

import android.text.InputFilter;
import android.text.Spanned;

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

/**
 * Describe 经纬度 限制输入整数和小数位数
 * Created by Bby on 2022/7/10
 * Email bby0856@163.com
 */
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 (".".equals(source) && "".equals(dest.toString())) {
            return "0.";
        }
        StringBuilder builder = new StringBuilder(dest);
        if ("".equals(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;
    }

}
