-- Written by Miata lover
-- Do not reuse/modify without permission!
local M = {}

wiperKeyPressed = false
local timer = 0
local wiperState = 0
local wiperSleep = 0
local spd = 0
local spdR = 0
local ignitionIndependent

local function init(jbeamData)
  electrics.values.wiperVal = 0
  electrics.values.wiperValR = 0
  electrics.values.wipers = 0
  wiperState = 0
  ignitionIndependent = jbeamData.ignitionIndependent or false
  wipersNode = jbeamData.wipersNode
  spd = 0
  spdR = 0
  
  for _, n in pairs(v.data.nodes) do
    if n.name == wipersNode then
      wipersNode = n.cid
      break
    end
  end
end

local function updateGFX(dt)
  if wiperKeyPressed then
    if wiperState == 0 then
	  wiperState = 1
      wiperSleep = 5
      timer = wiperSleep
      gui.message("Wipers: Slow", 2, "wiperMsg")
    elseif wiperState == 1 then
	  wiperState = 2
      wiperSleep = 0
      gui.message("Wipers: Fast", 2, "wiperMsg")
    else
	  wiperState = 0
      gui.message("Wipers: Off", 2, "wiperMsg")
    end
    wiperKeyPressed = false
	electrics.values.wipers = wiperState / 2
  end

  if wiperState ~= 0 and electrics.values.wiperVal == 0 and timer >= wiperSleep and electrics.values.ignitionLevel ~= 0 then
    spd = 1.5
    if electrics.values.gearIndex < 0 then spdR = 1.5 end
    timer = 0

    obj:createSFXSource2("art/sounds/wiper.mp3", "AudioDefault3D", "wiperSound", wipersNode, 0)
    obj:playSFXOnceCT("wiperSound", wipersNode, 1, 1, 0, 0)
  elseif electrics.values.wiperVal >= 1 then
    spd = -1
    spdR = -1
  elseif electrics.values.wiperVal > 0.9 and spd == 1.5 then
    spd = 1
    if electrics.values.wiperValR > 0 then spdR = 1 end
  elseif electrics.values.wiperVal < 0.9 and spd == -1 then
    spd = -1.5
    spdR = -1.5
  end

  if electrics.values.ignitionLevel ~= 0 or ignitionIndependent == true then
    electrics.values.wiperVal = electrics.values.wiperVal + (dt * spd)
    electrics.values.wiperValR = electrics.values.wiperValR + (dt * spdR)
  end

  if electrics.values.wiperVal < 0 then
    electrics.values.wiperVal = 0
    electrics.values.wiperValR = 0
    spd = 0 
    spdR = 0 
  end
  timer = timer + dt
end

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