package com.adealink.weparty.commonui.text

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import com.adealink.frame.log.Log
import com.adealink.weparty.commonui.text.span.DirtySpan

/**
 * DataBindingSpan配套EditText
 */
class DataBindingSpanEditText : AppCompatEditText {

    constructor(context: Context) : super(context)

    constructor(context: Context, attr: AttributeSet) : super(context, attr)

    constructor(context: Context, attr: AttributeSet, defStyle: Int) : super(context, attr, defStyle)

    override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        val spannable = getText() ?: return
        Log.d(TAG, "onTextChanged() called with: text = $text, start = $start, lengthBefore = $lengthBefore, lengthAfter = $lengthAfter")
        spannable.getSpans(0, spannable.length, DirtySpan::class.java)?.firstOrNull()?.let {
            if (it.isDirty(spannable)) {
                val spanStart = spannable.getSpanStart(it)
                val spanEnd = spannable.getSpanEnd(it)
                spannable.delete(spanStart, spanEnd)
            }
        }
    }

    companion object {
        const val TAG = "DataBindingSpanEditText"
    }
}