package com.erwan.revwatch.model

data class UnitOption(
    val key: String,
    val label: String,
    val factor: Double = 1.0,
    val offset: Double = 0.0,
    val minValue: Double,
    val maxValue: Double,
    val decimals: Int = 0
) {
    fun convert(value: Double): Double = value * factor + offset
    fun toRaw(displayValue: Double): Double = (displayValue - offset) / factor

    companion object {
        fun optionsFor(widget: WidgetType): List<UnitOption> = when (widget) {
            WidgetType.BOOST -> listOf(
                UnitOption("kpa", "kPa", 1.0, 0.0, -20.0, 160.0, 0),
                UnitOption("bar", "bar", 0.01, 0.0, -0.2, 1.6, 2),
                UnitOption("psi", "psi", 0.145038, 0.0, -2.9, 23.2, 1)
            )
            WidgetType.SPEED -> listOf(
                UnitOption("kmh", "km/h", 1.0, 0.0, 0.0, 260.0, 0),
                UnitOption("mph", "mph", 0.621371, 0.0, 0.0, 162.0, 0)
            )
            WidgetType.OIL_TEMP -> listOf(
                UnitOption("c", "\u00B0C", 1.0, 0.0, 40.0, 150.0, 0),
                UnitOption("f", "\u00B0F", 1.8, 32.0, 104.0, 302.0, 0)
            )
            WidgetType.COOLANT -> listOf(
                UnitOption("c", "\u00B0C", 1.0, 0.0, 40.0, 130.0, 0),
                UnitOption("f", "\u00B0F", 1.8, 32.0, 104.0, 266.0, 0)
            )
            WidgetType.RPM -> listOf(
                UnitOption("rpm", "rpm", 1.0, 0.0, 0.0, 7000.0, 0)
            )
            WidgetType.VOLTAGE -> listOf(
                UnitOption("v", "V", 1.0, 0.0, 10.5, 15.5, 1)
            )
            WidgetType.FUEL_LEVEL -> listOf(
                UnitOption("pct", "%", 1.0, 0.0, 0.0, 100.0, 0)
            )
            WidgetType.FUEL_RATE -> listOf(
                UnitOption("lh", "L/h", 1.0, 0.0, 0.0, 20.0, 1),
                UnitOption("galh", "gal/h", 0.264172, 0.0, 0.0, 5.3, 2)
            )
            WidgetType.FUEL_L100 -> listOf(
                UnitOption("l100", "L/100", 1.0, 0.0, 0.0, 30.0, 1)
            )
        }

        fun defaultFor(widget: WidgetType): UnitOption = optionsFor(widget).first()

        fun fromKey(widget: WidgetType, key: String?): UnitOption {
            return optionsFor(widget).firstOrNull { it.key == key } ?: defaultFor(widget)
        }
    }
}
