package com.lukouguoji.module_base.ktx

import android.text.InputFilter
import android.text.Spanned
import android.widget.EditText
import androidx.databinding.BindingAdapter


@BindingAdapter("setTextAllCaps")
fun setTextAllCaps(et: EditText, allCaps: Boolean) {
    if (allCaps) {
        et.filters = arrayOf<InputFilter>(InputFilter.AllCaps())
    } else {
        et.filters = emptyArray<InputFilter>()
    }
}

/**
 * 大写字母和数字输入过滤器
 * 只允许输入大写字母(A-Z)和数字(0-9),小写字母自动转为大写
 */
class UpperCaseAlphanumericInputFilter : InputFilter {
    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        if (source.isNullOrEmpty()) return null

        val filtered = StringBuilder()
        for (i in start until end) {
            val char = source[i]
            // 只允许ASCII字母(A-Z, a-z)和数字(0-9)
            if (char in 'A'..'Z' || char in 'a'..'z' || char in '0'..'9') {
                // 自动转为大写
                filtered.append(char.uppercaseChar())
            }
        }

        // 如果过滤后的内容与原内容相同,返回null表示不修改
        // 否则返回过滤后的内容
        return if (filtered.toString() == source.subSequence(start, end).toString()) {
            null
        } else {
            filtered.toString()
        }
    }
}

/**
 * 为 EditText 设置大写字母和数字输入过滤器
 * 使用方式: editText.setUpperCaseAlphanumericFilter()
 */
fun EditText.setUpperCaseAlphanumericFilter() {
    this.filters = arrayOf(UpperCaseAlphanumericInputFilter())
}

/**
 * 大写字母输入过滤器
 * 只允许输入大写字母(A-Z),小写字母自动转为大写
 */
class UpperCaseLetterInputFilter : InputFilter {
    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        if (source.isNullOrEmpty()) return null

        val filtered = StringBuilder()
        for (i in start until end) {
            val char = source[i]
            if (char in 'A'..'Z' || char in 'a'..'z') {
                filtered.append(char.uppercaseChar())
            }
        }

        return if (filtered.toString() == source.subSequence(start, end).toString()) {
            null
        } else {
            filtered.toString()
        }
    }
}

/**
 * 为 EditText 设置大写字母输入过滤器
 * 使用方式: editText.setUpperCaseLetterFilter()
 */
fun EditText.setUpperCaseLetterFilter() {
    this.filters = arrayOf(UpperCaseLetterInputFilter())
}