package ch.dissem.yaep.ui.common

import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.focus.onFocusEvent
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.unit.dp
import ch.dissem.yaep.ui.common.focus.FocusFollowingFocusable
import ch.dissem.yaep.ui.common.focus.Focusable

@Composable
fun Modifier.focus(focusable: Focusable<*>): Modifier {
    var m = this
    val hasFocus by focusable.hasFocus.collectAsState(false)
    if (hasFocus) {
        m = m.border(
            width = 2.dp,
            color = MaterialTheme.colorScheme.primary,
            shape = RectangleShape
        )
    }
    if (focusable is FocusFollowingFocusable) {
        m = m
            .focusRequester(focusable.focusRequester)
            .onFocusEvent { state ->
                focusable.setFocus(state)
            }
            .onFocusChanged {}
            .focusable()
    }
    return m
}