-- 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()
    if not emDisabled then
      setEmotorDirection(0)
      emDisabled = true
    else
      emDisabled = false
    end
end

local function toggleCombustionMotor()
    local curDevice = powertrain.getDevice("mainEngine")
    while curDevice.type ~= "shaft" do
        if not curDevice.children[1] then return end
        curDevice = curDevice.children[1]
    end

    --[[
    local hasDisconnectedMode = false
    for _, availableMode in ipairs(curDevice.availableModes) do
        if availableMode == "disconnected" then
            hasDisconnectedMode = true
        end
    end

    if not hasDisconnectedMode then
        table.insert(curDevice.availableModes, "disconnected")
    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
--[[
    for k, availableMode in ipairs(curDevice.availableModes) do
        if availableMode == "disconnected" then
            table.remove(curDevice.availableModes, k)
        end
    end]]
    curDevice:setMode("connected")
end

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

    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
        toggleCombustionMotor()
    elseif electrics.values.ignitionLevel == 1 then
        toggleCombustionMotor()
    end
end

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

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

return M