package com.gingersoft.gsa.cloud.common.utils.inputFilter;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;

import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/1/19
 * Time: 18:29
 * Use:
 */
public class DecimalDigitsInputFilter implements InputFilter {
    /**
     * 限制小数位数
     */
    private final int decimalDigits;
    private Context context;
    public DecimalDigitsInputFilter(Context context, int decimalDigits) {
        this.decimalDigits = decimalDigits;
        this.context = context;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int dotPos = -1;
        int len = dest.length();
        for (int i = 0; i < len; i++) {
            char c = dest.charAt(i);
            if (c == '.' || c == ',') {
                dotPos = i;
                break;
            }
        }

        if (source.equals(".") && dstart == 0 && dend == 0) {
            return "";
        }

        if (dotPos >= 0) {
            // protects against many dots
            if (source.equals(".") || source.equals(",")) {
                return "";
            }
            // if the text is entered before the dot
            if (dend <= dotPos) {
                return null;
            }
            if (len - dotPos > decimalDigits) {
                ToastUtils.show(context, "最多只能兩位小數");
                return "";
            }
        }

        return null;

    }

}
