package com.tenlionsoft.baselib.core.widget.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.R;
import com.tenlionsoft.baselib.utils.LogUtils;

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

/**
 * 作者: adam
 * 日期: 2021/9/18 - 5:01 下午
 * 邮箱: itgaojian@163.com
 * 描述: 带过滤器的输入框
 */
public class LimitEmojiEditText extends androidx.appcompat.widget.AppCompatEditText {
    private int mType = 1;//不限制   2:不能输入表情  3:身份证号码  4 :电话号码
    private Pattern mPattern;

    public LimitEmojiEditText(Context context) {
        super(context);
        initEditText();
    }


    public LimitEmojiEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LimitEmojiEditText);
        mType = ta.getInteger(R.styleable.LimitEmojiEditText_dataType, -1);
        initEditText();
    }

    public LimitEmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LimitEmojiEditText);
        mType = ta.getInteger(R.styleable.LimitEmojiEditText_dataType, -1);
        initEditText();
    }

    /**
     *
     */
    private void initEditText() {
        switch (mType) {
            case 1:
            default:
                this.setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
                break;
            case 2:
                mPattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                        Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
                this.setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
                break;
            case 3://身份证号码
                mPattern = Pattern.compile("[^0-9a-zA-Z_]");
                this.setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
                break;
            case 4://数字
                mPattern = Pattern.compile("[^0-9]",
                        Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
                this.setInputType(EditorInfo.TYPE_NUMBER_FLAG_SIGNED);
                break;
        }

        if (mPattern != null) {
            InputFilter inputFilter = (source, start, end, dest, dstart, dend) -> {
                LogUtils.e(source);
                Matcher emojiMatcher = mPattern.matcher(source);
                if (emojiMatcher.find()) {
                    //存在特殊字符
                    ToastUtils.show("不支持输入其他符号");
                    return "";
                }
                return null;
            };
            this.setFilters(new InputFilter[]{inputFilter});
        }
    }
}
