package theorycrafter.ui.graphs

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import compose.widgets.GraphLine
import eve.data.asDistance
import eve.data.millisAsTimeSec
import theorycrafter.fits.FitHandle
import theorycrafter.fitting.distanceTravelled


/**
 * The graphs window pane for exploring the distance travelled over time.
 */
@Composable
fun DistanceTravelledGraphPane(initialFitHandle: FitHandle?) {
    FitsGraphPane(
        initialFitHandle = initialFitHandle,
        graph = { fits, modifier ->
            DistanceTravelledGraph(
                fits = fits,
                modifier = modifier
            )
        }
    )
}


/**
 * The graph of the distance travelled over time of the given list of fits.
 */
@Composable
private fun DistanceTravelledGraph(
    fits: List<GraphFit>,
    modifier: Modifier
) {
    val maxDisplayedTime = 60.0
    val maxDisplayedDistance = fits.maxOfOrNull {
        distanceTravelled(
            maxVelocity = it.fit.propulsion.maxVelocity,
            mass = it.fit.propulsion.mass.value,
            inertiaModifier = it.fit.propulsion.inertiaModifier.value,
            timeSec = maxDisplayedTime
        )
    }?.plus(10_000) ?: 100_000.0 // 100km
    BasicGraph(
        modifier = modifier,
        xRange = 0.0 .. maxDisplayedTime,
        yRange = 0.0 .. maxDisplayedDistance,
        xValueFormatter = { (it*1000).millisAsTimeSec() },
        yValueFormatter = Double::asDistance,
        lines = fits.map { graphFit ->
            val propulsion = graphFit.fit.propulsion
            val maxVelocity = propulsion.maxVelocity
            GraphLine(
                name = graphFit.name,
                function = { time ->
                    distanceTravelled(
                        maxVelocity = maxVelocity,
                        mass = propulsion.mass.value,
                        inertiaModifier = propulsion.inertiaModifier.value,
                        timeSec = time
                    )
                },
                samplingStepPx = DefaultLineSamplingStep,
                lineStyleAtPoint = graphFit.lineStyle
            )
        }
    )
}

