--Code by Inn0centJok3r, updateGFX is a cutout from combustionEngine.lua
--Edited for my needs, feel free to use
local M = {}
M.type = "auxilliary"
M.relevantDevice = nil
local device = nil
local max = math.max
local min = math.min
local evEngineWaterDamageNode = "evWaterDamage"
local nodeID

local function updateGFX(dt) 
  if device.floodLevel > 0.9 then --0.9 is the threshold for "hydrolocking"
    return
  end

  -- engine starts flooding if ALL of the waterDamage nodes are underwater
  local isFlooding = device.canFlood
  
    isFlooding = isFlooding and obj:inWater(device.waterDamageNodes[nodeID])

  -- calculate flooding speed (positive) or drying speed (negative, and arbitrarily slower than flooding after some testing)
  local wetspeed = 0.2
  local dryspeed = -0.1
  local floodSpeed = (isFlooding and wetspeed or dryspeed)
  -- actual check for engine dying
  device.floodLevel = min(1, max(0, device.floodLevel + dt * floodSpeed))
  if device.floodLevel > 0.9 then
    damageTracker.setDamage("engine", "engineHydrolocked", true)
    -- turn off motors
	device:lockUp()
	device.isDisabled = true
	gui.message({txt = "Electric Circuits Shorted", context = {}}, 10, "vehicle.damage.flood")
    return
  end
end

local function init(jbeamData) 
  evEngineWaterDamageNode = jbeamData.evEngineWaterDamageNode or "evWaterDamage"	--ability to add node to look for via jbeam
  device = powertrain.getDevice("mainEngine")
  device.canFlood = false
  device.waterDamageNodes = {}	--Janky workaround as the code from the combustion engine lua didn't work here weirdly enough.
	for v, node in pairs (v.data.nodes) do
		if node.name == evEngineWaterDamageNode then	
		device.waterDamageNodes[node]=v
		nodeID = node
	    device.canFlood = true
		end
	end
  device.floodLevel = 0
end

local function reset() 
  device = powertrain.getDevice("mainEngine")
    damageTracker.setDamage("engine", "engineHydrolocked", false)
  device.floodLevel = 0
end

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

return M