-- Written by DaddelZeit.
-- Permission for usage is hereby granted to anyone owning this file.

local M = {}

local emDisabled = false
local lastGearIndex = 0

local function setEmotorDirection(val)
    for _, e in pairs (powertrain.getDevicesByType("electricMotor")) do
        e.motorDirection = val
    end
end

local function updateGear()
    if electrics.values.gearIndex == 0 then
        setEmotorDirection(0)
    elseif  electrics.values.gearIndex < 0 then
        setEmotorDirection(-1)
    elseif electrics.values.gearIndex > 0 then
        setEmotorDirection(1)
    end
end

local function toggleMotor()
    if not emDisabled then
      setEmotorDirection(0)
	  guihooks.message("Motor Disabled", 4, "vehicle.CRGZHybrid.evToggle", "power_settings_new")
      emDisabled = true
    else
      emDisabled = false
	  guihooks.message("Motor Enabled", 4, "vehicle.CRGZHybrid.evToggle", "power_settings_new")
      updateGear()
    end
end

local function updateGFX()
    if lastGearIndex == electrics.values.gearIndex then return end
    if emDisabled then return end

    updateGear()

    lastGearIndex = electrics.values.gearIndex
end

local function init()
    setEmotorDirection(0)
    emDisabled = false
end

M.toggleMotor = toggleMotor
M.init = init
M.updateGFX = updateGFX

return M