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

class GridSelectionManager : SelectionManager<GridFocusable>() {

    val grid = mutableListOf<MutableList<GridFocusable>>()

    var row = 0
    var col = 0

    fun addRow(): GridSelectionManager {
        grid.add(mutableListOf())
        return this
    }

    fun add(onKeyEvent: (KeyEvent) -> Boolean): GridFocusable {
        val new = GridFocusable(
            manager = this,
            primaryAction = null,
            secondaryAction = null,
            onKeyEvent = onKeyEvent,
            position = "${grid.last().size + 1}/${grid.size}"
        )
        grid.last().add(new)
        return new
    }

    override fun add(
        primaryAction: (() -> Unit)?,
        secondaryAction: (() -> Unit)?
    ): GridFocusable {
        val new = GridFocusable(
            manager = this,
            primaryAction = primaryAction,
            secondaryAction = secondaryAction,
            position = "${grid.last().size + 1}/${grid.size}"
        )
        grid.last().add(new)
        return new
    }

    override fun doOnKeyEvent(event: KeyEvent): Boolean {
        if (grid.isEmpty()) return false

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

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

            Key.DirectionRight -> {
                col++
                if (col >= grid[row].size) {
                    col = 0
                }
            }

            Key.DirectionLeft -> {
                col--
                if (col < 0) {
                    col = grid[row].size - 1
                }
            }

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

        focused = grid[row][col]
        return true
    }
}