-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt

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

local max = math.max
local min = math.min
local maxGear
local minRPM = 0
local maxRPM = 0
local aggression = 0

local function updateGFX(dt)
  local rpm = electrics.values["rpm"]
  local isOverMaxRPM = rpm >= maxRPM
--Custom lua for low rpm shift light
  if electrics.values["throttle"] >= 0.8 then
    aggression = min(1, aggression + dt * 2 * electrics.values["throttle"])
  elseif electrics.values["throttle"] < 0.8 then
    aggression = min(1, aggression - dt * 0.2 * (1-electrics.values["throttle"]))
  end
  if aggression <= 0.6 and rpm >= 2500 and electrics.values["gearIndex"] ~= maxGear and not isOverMaxRPM then
    electrics.values["shiftlight"] = 1
  elseif aggression > 0.6 and rpm >= minRPM and electrics.values["gearIndex"] ~= maxGear and not isOverMaxRPM then
    electrics.values["shiftlight"] = 1
  else
    electrics.values["shiftlight"] = 0
  end
end

local function init(jbeamData)
  maxRPM = 7000
  local rpmRange = jbeamData.rpmRange or 3000
  local gearbox = powertrain.getDevice("gearbox")
  if gearbox then
	maxGear = gearbox.maxGearIndex
	if gearbox.type == "automaticGearbox" or gearbox.type == "cvtGearbox" then
		M.updateGFX = nop
		electrics.values["shiftlight"] = 0
	end
  else
	M.updateGFX = nop
	electrics.values["shiftlight"] = 0
  end
  if jbeamData.engineName and jbeamData.maxEngineRPMOffset then
    local engine = powertrain.getDevice(jbeamData.engineName)
    if engine then
      maxRPM = engine.maxRPM - jbeamData.maxEngineRPMOffset
    end
  end
  maxRPM = jbeamData.maxRPM or maxRPM
  minRPM = maxRPM - rpmRange
  minRPM = jbeamData.minRPM or minRPM
end

local function reset()
  aggression = 0
end

M.reset = reset
M.init = init
M.updateGFX = updateGFX

return M
