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

import android.text.Editable
import android.text.TextWatcher
import com.adealink.frame.log.Log

class InputTextWatcher(val listener: OnWatchListener) : TextWatcher {

    private val watchTextSet = mutableSetOf<String>()

    fun addWatchText(text: String) {
        watchTextSet.add(text)
    }

    fun removeWatchText(text: String) {
        watchTextSet.remove(text)
    }

    fun clearWatchText() {
        watchTextSet.clear()
    }

    private var beforeText: String? = null

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        Log.d(TAG, "beforeTextChanged() called with: s = $s, start = $start, count = $count, after = $after")
        beforeText = s?.toString()
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        Log.d(TAG, "onTextChanged() called with: s = $s, start = $start, before = $before, count = $count")
        checkInputInWatch(beforeText, s, start, count)
    }

    override fun afterTextChanged(s: Editable?) {
        Log.d(TAG, "afterTextChanged() called with: s = $s")
    }

    private fun checkInputInWatch(beforeStr: CharSequence?, afterStr: CharSequence?, start: Int, count: Int): Boolean {
        if (watchTextSet.isEmpty()) {
            return false
        }
        if (afterStr.isNullOrEmpty()) {
            return false
        }
        if (beforeStr.isNullOrEmpty() || afterStr.length > beforeStr.length) { //输入内容的操作
            val text = afterStr.subSequence(start, start + count)
            Log.d(TAG, "checkInputInWatch, $text")
            if (watchTextSet.contains(text.toString())) {
                listener.onWatch(text)
            }
        }
        return false
    }

    interface OnWatchListener {
        fun onWatch(text: CharSequence)
    }

    companion object {
        private const val TAG = "InputTextWatcher"
    }
}