package com.remax.visualnovel.utils


import android.view.View
import androidx.core.view.*
import com.remax.visualnovel.utils.ResUtil.dp

fun View.setOnKeyboardVisibilityChangeListener(
    onShown: (keyboardHeight: Int) -> Unit,
    onHidden: () -> Unit
) {
    val threshold = 100.dp

    ViewCompat.setOnApplyWindowInsetsListener(this) { view, insets ->
        val imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime())
        val keyboardHeight = imeInsets.bottom

        val isKeyboardVisible = keyboardHeight > threshold

        if (isKeyboardVisible) {
            onShown(keyboardHeight)
        } else {
            onHidden()
        }

        insets
    }
}

fun View.setOnKeyboardHeightChangeListener(
    onHeightChanged: (keyboardHeight: Int, isVisible: Boolean) -> Unit
) {
    var lastKeyboardHeight = 0
    var lastVisibility = false

    ViewCompat.setOnApplyWindowInsetsListener(this) { view, insets ->
        val imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime())
        val keyboardHeight = imeInsets.bottom
        val isVisible = keyboardHeight > 100.dp

        if (keyboardHeight != lastKeyboardHeight || isVisible != lastVisibility) {
            onHeightChanged(keyboardHeight, isVisible)
            lastKeyboardHeight = keyboardHeight
            lastVisibility = isVisible
        }

        //WindowInsetsCompat.CONSUMED.toWindowInsets() ?: insets
        insets
    }
}

