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

import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key

class LinearSelectionManager(
    val keyNext: Key,
    val keyPrevious: Key? = null
) : SelectionManager<LinearFocusable>() {

    private fun focusNext() {
        focused = focused?.next
    }

    private fun focusPrevious() {
        focused = focused?.previous
    }

    override fun add(
        primaryAction: (() -> Unit)?,
        secondaryAction: (() -> Unit)?
    ): LinearFocusable {
        val new = LinearFocusable(
            manager = this,
            primaryAction = primaryAction,
            secondaryAction = secondaryAction
        )
        if (focused != null) {
            new.next = focused!!
        } else {
            focused = new
        }
        return new
    }

    override fun doOnKeyEvent(event: KeyEvent): Boolean {
        if (event.key == keyNext) {
            if (keyPrevious == null && event.isShiftPressed) {
                focusPrevious()
            } else {
                focusNext()
            }
        } else if (event.key == keyPrevious) {
            focusPrevious()
        } else {
            return focused?.child?.onKeyEvent(event) == true
        }
        return true
    }
}