local M = {}
M.type = "auxiliary"
M.relevantDevice = nil

local throttle_locked = false -- Flag to track if the throttle should be locked
local watertempflashTimer = 0
local flashInterval = 0.5 -- Flash interval in seconds

local engine = nil

local rpmToAV = 0.104719755
local need_to_reset = false
local tempRevLimiterAV = 0
local tempRevLimiterRPM = 0

local function updateGFX(dt)
  -- Rev limiter logic (activated only when throttle_locked is true and gear is R, D, 2, or 1)
  if throttle_locked then
    if electrics.values['gear'] == "R" or electrics.values['gear'] == "D" or
       electrics.values['gear'] == "2" or electrics.values['gear'] == "1" then
      engine:setTempRevLimiter(tempRevLimiterAV)
      need_to_reset = true
    elseif need_to_reset then
      engine:resetTempRevLimiter()
      need_to_reset = false
    end
  else
    -- Reset rev limiter when throttle_locked becomes false
    if need_to_reset then
      engine:resetTempRevLimiter()
      need_to_reset = false
    end
  end
  
  -- Water temperature logic
  if electrics.values.watertemp > 125 then
    throttle_locked = true -- Set flag to true once water temperature exceeds 125
    electrics.values.watertempwarn = 1 -- Activate water temperature warning
  elseif electrics.values.watertemp <= 120 then
    throttle_locked = false -- Reset flag once water temperature falls below 120
    electrics.values.watertempwarn = 0 -- Deactivate water temperature warning
  end
  
  -- Limit the throttle to 0.25 if the flag is set
  if throttle_locked then
    electrics.values.throttle = math.min(electrics.values.throttle, 0.25)
    
    watertempflashTimer = watertempflashTimer + dt
    if watertempflashTimer >= flashInterval then
      electrics.values.watertempflash = 1 - electrics.values.watertempflash -- Toggle between 0 and 1
      watertempflashTimer = watertempflashTimer - flashInterval
    end

    electrics.values.watertempwarn = 1
    electrics.values.waterwarn = 0 -- Set waterwarn to 0 when watertemp is above 125
  else
    electrics.values.throttle = math.min(electrics.values.throttle, 1) -- Ensure the throttle is not locked
    electrics.values.watertempflash = 0
    watertempflashTimer = 0
    electrics.values.watertempwarn = 0
  end
end

local function reset()
  electrics.values.throttle = 1 -- Reset throttle to its original state when the car is reset
  throttle_locked = false -- Reset the flag
  
  if engine then
    engine:resetTempRevLimiter()
    need_to_reset = false
  end
end

local function init(jbeamData)
  M.updateGFX = updateGFX
  M.reset = reset

  local engineName = jbeamData.engineName or "mainEngine"
  engine = powertrain.getDevice(engineName)
  if engine then
    tempRevLimiterRPM = 6000
    tempRevLimiterAV = tempRevLimiterRPM * rpmToAV
  end
end

M.init = init
M.reset = reset

return M