package com.remax.visualnovel.extension

import android.view.KeyEvent
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.internal.ThreadUtil
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch

/**
 * 搜索框防抖
 * tips: flow流需要在协程中创建，使用当前EditText的activity.lifecycleOwner创建，搜索不走的话，需要另行创建协程
 */
fun EditText.startSearch(resInvoke: (res: String) -> Unit) {
    (context.findActivityContext() as? AppCompatActivity)?.run {
        lifecycleScope.launch {
            textChangeFlow()
                .debounce(500)
                .collect {
                    resInvoke.invoke(it)
                }
        }
    }
}

private fun EditText.textChangeFlow(): Flow<String> {
    return callbackFlow {
        require(ThreadUtil.isMainThread())
        val listener = doOnTextChanged { text, _, _, _ -> trySend(text?.toString() ?: "") }
        awaitClose { removeTextChangedListener(listener) }
    }
}

/**
 * 屏蔽回车换行
 */
fun EditText.filterEnter() {
    this.setOnEditorActionListener { _, _, event ->
        (event?.keyCode ?: 0) == KeyEvent.KEYCODE_ENTER
    }
}

/**
 * 输入框不允许输入换行符
 */
fun EditText.withoutNewLineChanges(resInvoke: (res: CharSequence) -> Unit) {
    this.run {
        filterEnter()
        doAfterTextChanged {
            if (this.isFocused) {
                if (it?.contains("\n") == true) {
                    val content = it.toString().replace("\n", "")
                    this.setText(content)
                    this.setSelection(content.length)
                } else {
                    resInvoke.invoke(it?.toString() ?: "")
                }
            }
        }
    }
}
