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

import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.util.fastRoundToInt
import com.pixelized.desktop.lwa.ui.composable.scene.camera.Camera

/**
 * Convert local positon to global one.
 * Global position are agnostic from camera, and therefor should be use to position stuff on the map.
 * A common use case is to share players cursor.
 */
fun Offset.global(
    camera: Camera,
): Offset = global(
    zoom = camera.zoom,
    offset = camera.offset,
)

/**
 * Convert local positon to global one.
 * Global position are agnostic from camera, and therefor should be use to position stuff on the map.
 * A common use case is to share players cursor.
 */
fun Offset.global(
    zoom: Float,
    offset: IntOffset,
): Offset = Offset(
    x = this.x * zoom + offset.x,
    y = this.y * zoom + offset.y,
)

/**
 * Convert global positon to local one.
 * Local position take into account the camera and are use to display stuff on the Scene composable.
 */
fun Offset.local(
    camera: Camera,
): Offset = local(
    zoom = camera.zoom,
    offset = camera.offset,
)

/**
 * Convert global positon to local one.
 * Local position take into account the camera and are use to display stuff on the Scene composable.
 */
fun Offset.local(
    zoom: Float,
    offset: IntOffset,
): Offset = Offset(
    x = (this.x - offset.x) / zoom,
    y = (this.y - offset.y) / zoom,
)

/**
 * Convert local positon to global one.
 * Global position are agnostic from camera, and therefor should be use to position stuff on the map.
 * A common use case is to share players cursor.
 */
fun Offset.globalInt(
    camera: Camera,
): IntOffset = globalInt(
    zoom = camera.zoom,
    offset = camera.offset,
)

/**
 * Convert local positon to global one.
 * Global position are agnostic from camera, and therefor should be use to position stuff on the map.
 * A common use case is to share players cursor.
 */
fun Offset.globalInt(
    zoom: Float,
    offset: IntOffset,
): IntOffset = IntOffset(
    x = (this.x * zoom + offset.x).fastRoundToInt(),
    y = (this.y * zoom + offset.y).fastRoundToInt(),
)

/**
 * Convert global positon to local one.
 * Local position take into account the camera and are use to display stuff on the Scene composable.
 */
fun Offset.localInt(
    camera: Camera,
): IntOffset = localInt(
    zoom = camera.zoom,
    offset = camera.offset,
)

/**
 * Convert global positon to local one.
 * Local position take into account the camera and are use to display stuff on the Scene composable.
 */
fun Offset.localInt(
    zoom: Float,
    offset: IntOffset,
): IntOffset = IntOffset(
    x = ((this.x - offset.x) / zoom).fastRoundToInt(),
    y = ((this.y - offset.y) / zoom).fastRoundToInt(),
)