package mg.dot.feufaro.midi

import java.util.prefs.Preferences

enum class Dynamic(val velocity: Int, val label: String, val defaultFactor: Float) {
    PPP(16,  "ppp", 0.55f),
    PP (33,  "pp",  0.66f),
    P  (49,  "p",   0.77f),
    MP (64,  "mp",  0.88f),
    MF (80,  "mf",  1.00f),
    F  (96,  "f",   1.15f),
    FF (112, "ff",  1.35f),
    FFF(126, "fff", 1.60f);
    private val prefs = Preferences.userRoot().node("mg.dot.feufaro")
    var savedFactor: Float = prefs.getFloat("dynamic_${name.lowercase()}", defaultFactor)
        set(value) {
            field = value
            prefs.putFloat("dynamic_${name.lowercase()}", value)
        }

    val factor: Float
        get() = if (isGloballyEnabled) savedFactor else 1.00f

    companion object {
        private val globalPrefs = Preferences.userRoot().node("mg.dot.feufaro")
        var isGloballyEnabled: Boolean = globalPrefs.getBoolean("dynamics_enabled", true)
            set(value) {
                field = value
                globalPrefs.putBoolean("dynamics_enabled", value)
            }

        fun fromVelocity(v: Int): Dynamic =
            entries.minByOrNull { kotlin.math.abs(it.velocity - v) } ?: MF

        fun resetToDefaults() {
            entries.forEach { it.savedFactor = it.defaultFactor }
        }
    }
}