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.key
import ch.dissem.yaep.ui.common.ceilDiv
import kotlin.math.max
import kotlin.math.min

class CluesSelectionManager : SelectionManager<CluesFocusable>() {
    var columns: Int = 1

    private var row: Int = 0
    private var col: Int = 0

    private val focusables = mutableListOf<CluesFocusable>()

    override fun add(
        primaryAction: (() -> Unit)?,
        secondaryAction: (() -> Unit)?
    ): CluesFocusable {
        val new = CluesFocusable(
            manager = this,
            primaryAction = primaryAction,
            secondaryAction = secondaryAction
        )
        focusables.add(new)
        return new
    }

    override fun doOnKeyEvent(event: KeyEvent): Boolean {
        val rows = focusables.size ceilDiv columns

        when (event.key) {
            Key.DirectionDown -> {
                row++
                if (row >= rows) {
                    row = 0
                }
            }

            Key.DirectionUp -> {
                row--
                if (row < 0) {
                    row = rows - 1
                }
            }

            Key.DirectionRight -> {
                col++
                if (col >= columns) {
                    col = 0
                }
            }

            Key.DirectionLeft -> {
                col--
                if (col < 0) {
                    col = columns - 1
                }
            }

            else -> return focused?.child?.onKeyEvent(event) == true
        }

        // This makes sure the limits aren't exceeded when values are changed concurrently
        val index = max(0, min(row * columns + col, focusables.size - 1))
        focused = focusables[index]

        return true
    }
}