local M = {}
M.type = "auxilliary"
M.relevantDevice = nil
local batteryApplied = false
local storage = nil
local storage2 = nil
local msgShownLow = false
local msgShownVeryLow = false

local function checkIfBatteryApplied(storage)
  device = powertrain.getDevice("mainEngine")
  for _, s in pairs(device.registeredEnergyStorages) do
	storage = energyStorage.getStorage(s)
  end
  if storage then
	  if storage.energyType ~= "electricEnergy" then
		batteryApplied = false
		return
	  end
	batteryApplied = true
  end
end

local function updateGFX(dt) 
	if batteryApplied == true then

		device = powertrain.getDevice("mainEngine")
		for _, s in pairs(device.registeredEnergyStorages) do
			if not storage then
				storage = energyStorage.getStorage(s)
			elseif storage then
				storage2 = energyStorage.getStorage(s)
			end
		end

		if storage then -- calculate combined energy
			if storage2 then 
				totalEnergyInBatteries = storage.storedEnergy + storage2.storedEnergy
			else
				totalEnergyInBatteries = storage.storedEnergy
			end
			if totalEnergyInBatteries <= 10000000 then	--kinda compliated function to control throttle at low battery life. -1.7x^3 + 2.5x^2 +0.2
				electrics.values.throttleOverride = input.throttle * (-1.7 * math.pow(totalEnergyInBatteries/10000000, 3) + 2.5 * math.pow(totalEnergyInBatteries/10000000, 2) + 0.2)
				if totalEnergyInBatteries <= 7500000 and msgShownLow == false then
					guihooks.message("Low Battery charge. Power is reduced.", 6, "vehicle.vertexBattery.lowBattery", "battery_alert") 
					msgShownLow = true
				elseif totalEnergyInBatteries <= 4000000 and msgShownVeryLow == false then
					guihooks.message("Very low battery charge. Power is reduced.", 6, "vehicle.vertexBattery.lowBattery", "battery_alert") 
					msgShownVeryLow = true
				end
			else
				electrics.values.throttleOverride = nil	
			end
		end
	end
end

local function init() 
	electrics.values.throttleOverride = nil
	checkIfBatteryApplied()
	msgShownLow = false
	msgShownVeryLow = false
end

local function reset() 
	electrics.values.throttleOverride = nil
	checkIfBatteryApplied()
	msgShownLow = false
	msgShownVeryLow = false
end

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

return M