-- required modules
local latch = require("latch")
local debug = require("debugutil")("brakeLights", true)

-- module
local M = {
    type = "auxiliary",
    relevantDevice = nil,
    defaultOrder = 1000,
    
    -- properties
    jbeamData = nil,
    activeGears = nil,
    lightsLatch = nil,
    accelSmoother = nil,
    electricsName = nil,
    electricsOnValue = nil,
    
    -- state
    lastSpeed = 0,
}

function M.updateGFX(dt)
    local currentSpeed = electrics.values.wheelspeed
    local acceleration = M.accelSmoother:get((currentSpeed - M.lastSpeed) / dt, dt) -- m/s/s
    
    if M.activeGears[electrics.values.gear] and M.lightsLatch:test(-acceleration) then
        electrics.values[M.electricsName] = math.max(electrics.values[M.electricsName], M.electricsOnValue)
    end
    
    M.lastSpeed = currentSpeed
    
    debug.putValue("Speed (M/S)", currentSpeed)
    debug.putValue("Acceleration (M/S/S)", acceleration)
    debug.putValue("Latch", M.lightsLatch.state)
end

function M.init(jbeamData)
    M.jbeamData = jbeamData
    
    M.electricsName = jbeamData.electricsName or "brakelights"
    M.electricsOnValue = jbeamData.electricsOnValue or 1
    
    if type(jbeamData.activeGears) == "string" then
        M.activeGears = {}
        
        for i = 1, string.len(jbeamData.activeGears) do
            local gear = string.sub(jbeamData.activeGears, i, i)
            
            M.activeGears[gear] = true
        end
    else
        M.activeGears = {["D"] = true, ["L"] = true}
    end
    
    M.lightsLatch = latch.newThresholdLatch(
        jbeamData.decelForBrakeLightsOn  or 1.3,
        jbeamData.decelForBrakeLightsOff or 0.5
    )
    
    M.accelSmoother = newTemporalSmoothingNonLinear(jbeamData.accelSmoothing or 5.5)
end

return M