package com.erwan.revwatch.model

/**
 * Custom min/max display range + warning/danger thresholds per gauge.
 * All values are stored in RAW sensor units (°C, kPa, rpm, etc.)
 * and converted to display units via UnitOption when rendered.
 */
data class GaugeRange(
    val minValue: Double,
    val maxValue: Double,
    val warningLow: Double? = null,
    val dangerLow: Double? = null,
    val warningHigh: Double? = null,
    val dangerHigh: Double? = null
) {
    fun toLimits(): GaugeLimits = GaugeLimits(warningLow, dangerLow, warningHigh, dangerHigh)

    fun serialize(): String = listOf(
        minValue.toString(),
        maxValue.toString(),
        warningLow?.toString() ?: "",
        dangerLow?.toString() ?: "",
        warningHigh?.toString() ?: "",
        dangerHigh?.toString() ?: ""
    ).joinToString(",")

    companion object {
        fun defaultFor(widget: WidgetType, vehicle: VehicleProfile? = null): GaugeRange {
            if (vehicle != null) return vehicle.rangeFor(widget)
            val limits = GaugeLimits.forWidget(widget)
            return GaugeRange(
                minValue = widget.minValue,
                maxValue = widget.maxValue,
                warningLow = limits.warningLow,
                dangerLow = limits.dangerLow,
                warningHigh = limits.warningHigh,
                dangerHigh = limits.dangerHigh
            )
        }

        fun deserialize(s: String?): GaugeRange? {
            if (s.isNullOrBlank()) return null
            val parts = s.split(",")
            if (parts.size != 6) return null
            return GaugeRange(
                minValue = parts[0].toDoubleOrNull() ?: return null,
                maxValue = parts[1].toDoubleOrNull() ?: return null,
                warningLow = parts[2].toDoubleOrNull(),
                dangerLow = parts[3].toDoubleOrNull(),
                warningHigh = parts[4].toDoubleOrNull(),
                dangerHigh = parts[5].toDoubleOrNull()
            )
        }
    }
}
