package com.adealink.weparty.commonui.text.filter

import android.text.InputFilter
import android.text.InputType
import android.text.Spanned
import android.widget.EditText
import java.util.regex.Pattern

fun EditText.addNoWhitespaceInputFilter() {
    addFilter(NoWhitespaceInputFilter())
}

class NoWhitespaceInputFilter : InputFilter {

    // 定义不允许的字符：空格、换行、制表符等空白字符
    private val disallowedPattern = Pattern.compile("\\s")

    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence {
        source ?: return ""

        val filtered = StringBuilder()
        for (i in start until end) {
            val char = source[i]
            val charStr = char.toString()

            // 检查是否是空白字符
            if (!disallowedPattern.matcher(charStr).find()) {
                filtered.append(char)
            }
        }

        return if (filtered.length == end - start) {
            // 所有字符都有效，返回null保持原样
            source
        } else {
            // 有字符被过滤，返回过滤后的结果
            filtered.toString()
        }
    }
}