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

local speed = 0
local brake = 0
local throttle = 0
local speedFactor = 0
local efficiencyNeedleSmoother = newExponentialSmoothing(20)
local gaugeType

local function lerp(a,b,t) 
    return a * (1-t) + b * t 
end

local function clamp(min, max, val)
	if val < min then
		val = min
	elseif max < val then
		val = max
	end
	return val
end

local function updateGFX(dt) 

	if electrics.values["wheelspeed"] == nil then 
		electrics.values["efficiencyNeedle"] = 0.2
	return
	end
	
	speed = electrics.values["wheelspeed"]
	brake = electrics.values["brake"]
	throttle = electrics.values["throttle"]
	speedFactor = clamp(0, 1, lerp(0, 1, speed/13.888))	--maximum charging can be reached at 50km/h / 13.888 m/s = 50km/h a + (b - a) * t

  if gaugeType == "ice" then
	  if throttle == 0 then
		electrics.values["efficiencyNeedle"] = 0.01
		electrics.values["efficiencyNeedle"] = efficiencyNeedleSmoother:get(electrics.values["efficiencyNeedle"])
	  elseif throttle > 0 then
		electrics.values["efficiencyNeedle"] = lerp(0, 0.99, throttle) + 0.01
		electrics.values["efficiencyNeedle"] = efficiencyNeedleSmoother:get(electrics.values["efficiencyNeedle"])
	  else	
		electrics.values["efficiencyNeedle"] = 0.01
		electrics.values["efficiencyNeedle"] = efficiencyNeedleSmoother:get(electrics.values["efficiencyNeedle"])
	  end
  elseif gaugeType == "electric" then
	  if throttle == 0 and speed <= 0.2 then
		electrics.values["efficiencyNeedle"] = 0.2
		electrics.values["efficiencyNeedle"] = efficiencyNeedleSmoother:get(electrics.values["efficiencyNeedle"])
	  elseif throttle > 0 and speed > 0.2 then
		electrics.values["efficiencyNeedle"] = lerp(0, 0.9, throttle) + 0.2 --to move the needle to the 0 position so that the throttle factor then can move the needle up from there
		electrics.values["efficiencyNeedle"] = efficiencyNeedleSmoother:get(electrics.values["efficiencyNeedle"])
	  elseif speed > 0.2 and throttle <= 0.1 then
		electrics.values["efficiencyNeedle"] = 0.2 - lerp(0, 0.1, brake * speedFactor) - lerp(0, 0.1, speedFactor)
		electrics.values["efficiencyNeedle"] = efficiencyNeedleSmoother:get(electrics.values["efficiencyNeedle"])
	  else	
		electrics.values["efficiencyNeedle"] = 0.2
		electrics.values["efficiencyNeedle"] = efficiencyNeedleSmoother:get(electrics.values["efficiencyNeedle"])
	  end
  end
end

local function init(jbeamData)
	electrics.values["efficiencyNeedle"] = 0
	gaugeType = jbeamData.gaugeType or "ice"
	speed = 0
	brake = 0
	throttle = 0
	speedFactor = 0
end 

M.updateGFX = updateGFX
M.init = init
return M