package com.pixelized.desktop.lwa.ui.composable.scene.fogOfWar

import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.isPrimaryPressed
import androidx.compose.ui.input.pointer.onPointerEvent
import com.pixelized.desktop.lwa.ui.composable.scene.camera.Camera
import com.pixelized.desktop.lwa.ui.composable.scene.utils.global
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@OptIn(ExperimentalComposeUiApi::class)
fun Modifier.onFogOfWarControl(
    scope: CoroutineScope,
    enable: Boolean,
    camera: Camera,
    fogOfWar: FogOfWar,
) = if (!enable) {
    this
} else {
    var lastEventTime = System.currentTimeMillis()
    var previousEvent: PointerEvent? = null

    this
        .onPointerEvent(PointerEventType.Release) { _: PointerEvent ->
            scope.launch {
                println("PointerEventType.Release")
                lastEventTime = System.currentTimeMillis()
                previousEvent = null
            }
        }
        .onPointerEvent(PointerEventType.Move) { event: PointerEvent ->
            scope.launch {
                val pointer = event.changes.firstOrNull()
                val time = pointer?.uptimeMillis ?: 0L

                if (time - lastEventTime > 10L && event.buttons.isPrimaryPressed) {
                    if (previousEvent?.buttons?.isPrimaryPressed == true) {
                        println("PointerEventType.LineTo")
                        pointer?.position
                            ?.global(camera = camera)
                            ?.let(fogOfWar::lineTo)
                    } else {
                        println("PointerEventType.MoveTo")
                        pointer?.position
                            ?.global(camera = camera)
                            ?.let(fogOfWar::moveTo)
                    }
                    lastEventTime = System.currentTimeMillis()
                    previousEvent = event
                }
            }
        }
}