package com.tenlionsoft.baselib.core.widget;

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

/**
 * 作者: adam
 * 日期: 2022/4/13 - 6:01 下午
 * 邮箱: itgaojian@163.com
 * 描述: 限制输入长度
 */
public class AstrictLengthFilter implements InputFilter {
    private int mMax;
    private LengthListener mLengthListener;
    String regEx = "[\\u4e00-\\u9fa5]";

    public AstrictLengthFilter(int mAX_EN) {
        super();
        mMax = mAX_EN;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int keep = mMax - (dest.length() - (dend - dstart));
        if (keep <= 0) {
            if (null != mLengthListener) {
                mLengthListener.pass();
            }
            return "";
        } else if (keep >= end - start) {
            return null;
        } else {
            keep += start;
            if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                --keep;
                if (keep == start) {
                    return "";
                }
            }
            return source.subSequence(start, keep);
        }
    }

    public interface LengthListener {
        void pass();
    }

    public void addListener(LengthListener listener) {
        this.mLengthListener = listener;
    }
}
