package ch.dissem.yaep.ui.common.focus

import androidx.compose.ui.input.key.KeyEvent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine

abstract class Focusable<F : Focusable<F>>(
    protected val manager: SelectionManager<F>,
    val primaryAction: (() -> Unit)?,
    val secondaryAction: (() -> Unit)?,
    var onKeyEvent: ((KeyEvent) -> Boolean)? = null
) {

    val hasFocus: Flow<Boolean> =
        combine(manager.isActiveFlow, manager.focusedFlow) { isActive, focused ->
            isActive && focused == this
        }

    var child: SelectionManager<*>? = null
        private set

    fun <M : SelectionManager<*>> create(selectionManager: M): M = selectionManager.apply {
        isActive = manager.isActive && manager.focused == this@Focusable
        this@Focusable.child = this
    }

}