package com.erwan.revwatch.model

import com.erwan.revwatch.R

enum class WidgetType(
    val key: String,
    val displayName: String,
    val unit: String,
    val minValue: Double,
    val maxValue: Double,
    val accentColorRes: Int
) {
    OIL_TEMP("oil_temp", "Huile", "C", 40.0, 150.0, R.color.watch_hot),
    BOOST("boost", "Turbo", "kPa", -20.0, 160.0, R.color.watch_boost),
    RPM("rpm", "RPM", "rpm", 0.0, 7000.0, R.color.watch_rpm),
    SPEED("speed", "Vitesse", "km/h", 0.0, 260.0, R.color.watch_speed),
    COOLANT("coolant", "Eau", "C", 40.0, 130.0, R.color.watch_coolant),
    VOLTAGE("voltage", "Batterie", "V", 10.5, 15.5, R.color.watch_voltage),
    FUEL_LEVEL("fuel_level", "Essence", "%", 0.0, 100.0, R.color.watch_speed),
    FUEL_RATE("fuel_rate", "Conso.", "L/h", 0.0, 20.0, R.color.watch_rpm),
    FUEL_L100("fuel_l100", "L/100km", "L/100", 0.0, 30.0, R.color.watch_rpm);

    fun readFrom(snapshot: MetricSnapshot): Double? = when (this) {
        OIL_TEMP -> snapshot.oilTempC
        BOOST -> snapshot.boostKpa
        RPM -> snapshot.rpm
        SPEED -> snapshot.speedKph
        COOLANT -> snapshot.coolantTempC
        VOLTAGE -> snapshot.voltage
        FUEL_LEVEL -> snapshot.fuelLevelPct
        FUEL_RATE -> snapshot.fuelRateLph
        FUEL_L100 -> {
            val rate = snapshot.fuelRateLph
            val speed = snapshot.speedKph
            if (rate != null && speed != null) {
                if (speed > 0.1) (rate / speed * 100.0).coerceAtMost(99.9) else 99.9
            } else null
        }
    }

    companion object {
        fun fromKey(key: String?): WidgetType? {
            return entries.firstOrNull { it.key == key }
        }
    }
}
