package com.pixelized.desktop.lwa.ui.composable.key

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.input.key.KeyEvent

typealias KeyEventHandler = (KeyEvent) -> Boolean

val LocalKeyEventHandlers = staticCompositionLocalOf<MutableList<KeyEventHandler>> {
    error("LocalKeyEventHandlers is not provided")
}

@Composable
fun KeyHandler(
    key: Any = "KeyHandler",
    enabled: Boolean = true,
    onKeyPress: (KeyEvent) -> Boolean,
) {
    if (enabled) {
        val handlerState = rememberUpdatedState(onKeyPress)
        val eventHandlers = LocalKeyEventHandlers.current
        DisposableEffect(key) {
            val localHandler: KeyEventHandler = {
                handlerState.value(it)
            }
            eventHandlers.add(localHandler)
            onDispose {
                eventHandlers.remove(localHandler)
            }
        }
    }
}