package com.adealink.weparty.commonui.text.watcher

import android.text.Editable
import android.text.TextWatcher

// 配合 TextWatcher 实现自动替换
class AutoReplaceTextWatcher(
    private val maxValue: Double,
    private val maxDecimalDigits: Int = 2,
    private val setSelection: (position: Int) -> Unit,
    private val afterTextChanged: (text: String) -> Unit
) : TextWatcher {

    private var isReplacing = false

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

    override fun afterTextChanged(s: Editable?) {
        if (isReplacing || s == null) {
            afterTextChanged.invoke("")
            return
        }

        val text = s.toString()
        if (text.isEmpty()) {
            afterTextChanged.invoke("")
            return
        }

        // 处理以小数点开头
        if (text == ".") {
            isReplacing = true
            s.clear()
            s.append("0.")
            setSelection.invoke(s.length)
            afterTextChanged.invoke("0.")
            isReplacing = false
            return
        }

        // 转换为数字检查
        val value = text.toDoubleOrNull()
        if (value != null && value > maxValue) {
            isReplacing = true

            // 替换为最大值
            val maxValueStr = formatMaxValue(maxValue)
            s.clear()
            s.append(maxValueStr)

            // 光标移到最后
            setSelection.invoke(s.length)
            afterTextChanged.invoke(maxValueStr)
            isReplacing = false
            return
        }

        // 处理小数位数
        val dotIndex = text.indexOf('.')
        if (dotIndex != -1) {
            val decimalPart = text.substring(dotIndex + 1)
            if (decimalPart.length > maxDecimalDigits) {
                isReplacing = true
                s.delete(dotIndex + maxDecimalDigits + 1, s.length)
                isReplacing = false
            }
        }

        afterTextChanged.invoke(text)
    }

    private fun formatMaxValue(value: Double): String {
        val formatted = String.format("%.${maxDecimalDigits}f", value)
        return formatted.trimEnd('0').trimEnd('.')
    }
}