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

import android.text.Spannable
import com.adealink.weparty.commonui.text.span.DirtySpan
import kotlin.reflect.KClass

class DirtySpanWatcher<T : Any>(
    private val kClass: KClass<T>,
    private val removePredicate: (T) -> Boolean
) : SpanWatcherAdapter() {

    override fun onSpanChanged(
        text: Spannable, what: Any, ostart: Int, oend: Int, nstart: Int,
        nend: Int
    ) {
        if (what is DirtySpan && what.isDirty(text)) {
            val spanStart = text.getSpanStart(what)
            val spanEnd = text.getSpanEnd(what)
            text.getSpans(spanStart, spanEnd, kClass.java).firstOrNull()?.let {
                if (removePredicate.invoke(it)) {
                    text.removeRange(spanStart, spanEnd)
                }
            }
        }
    }

}