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

import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.graphicsLayer
import com.pixelized.desktop.lwa.ui.composable.scene.camera.Camera

fun Modifier.drawFogOfWar(
    camera: Camera,
    fogOfWar: FogOfWar,
): Modifier = this
    .graphicsLayer(
        compositingStrategy = CompositingStrategy.Offscreen
    )
    .drawWithCache {
        val stroke = Stroke(
            width = 32f,
            cap = StrokeCap.Round,
            join = StrokeJoin.Round
        )
        val fog = Color.Black.copy(alpha = 0.5f)
        val color = Color.Transparent
        onDrawBehind {
            drawRect(
                color = fog,
            )
            scale(
                scale = 1 / camera.zoom,
                pivot = Offset.Zero,
            ) {
                translate(
                    left = -camera.offset.x.toFloat(),
                    top = -camera.offset.y.toFloat(),
                ) {
                    drawPath(
                        path = fogOfWar.path.value,
                        style = stroke,
                        color = color,
                        blendMode = BlendMode.Clear,
                    )
                }
            }
        }
    }