-- 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 toggleMotor()
    local curDevice = powertrain.getDevice("mainEngine")
    while curDevice.type ~= "shaft" do
        if not curDevice.children[1] then return end
        curDevice = curDevice.children[1]
    end

    if electrics.values.ignitionLevel >= 2 then
        electrics.setIgnitionLevel(1)
        curDevice.isPhysicallyDisconnected = true
    elseif electrics.values.ignitionLevel == 1 then
        electrics.setIgnitionLevel(3)
        curDevice.isPhysicallyDisconnected = false
    end

    curDevice:setMode("connected")
end

local function updateGFX()

    if electrics.values.ignitionLevel == 0 then return end
    if lastGearIndex == electrics.values.gearIndex then return end

    -- Custom logic to control the electric motor based on gear index
    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

    lastGearIndex = electrics.values.gearIndex
end

local function setParameters(params)
    if params.combustionOff and electrics.values.ignitionLevel >= 2 then
        toggleMotor()
    elseif electrics.values.ignitionLevel == 1 then
        toggleMotor()
    end
end

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

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

return M
