local M = {}

local alarmSounded = false
local alarmNode = nil
local lastSetting = 0

local function init()
  alarmSounded = false
  lastSetting = 0
  electrics.values.rv5m_flag = 0
  electrics.values.rv5m_enabled = 0
  
  for _, node in ipairs(v.data.nodes) do
    local isAlarmNode = node.instrumentSoundEmitter or false
    if isAlarmNode then
      alarmNode = node
      break
    end
  end
end

local function soundAlarm()
  if alarmNode == nil then return end
  sounds.playSoundOnceAtNode("omi_1", alarmNode.cid, 5)	--Play the alarm sound
end

local function updateGFX(dt)
  local targetHeight = electrics.values[M.components["index"].input_electric]
  local currentHeight = electrics.values[M.components["needle"].input_electric]
  
  --prevent alarm from sounding on a setting change
  if targetHeight ~= lastSetting then
    alarmSounded = true
    lastSetting = targetHeight
  end
  
  --logic
  if targetHeight <= 0 then
    electrics.values.rv5m_enabled = 0
    electrics.values.rv5m_flag = 0
    return 
  end
  
  --from here on out, this code only runs if the instrument is enabled
  electrics.values.rv5m_enabled = 1
  if currentHeight < targetHeight then
    electrics.values.rv5m_flag = 1
    if not alarmSounded then
      soundAlarm()
      alarmSounded = true
    end
  else
    electrics.values.rv5m_flag = 0
    alarmSounded = false
  end
end

--public API
M.onInit = init
M.updateGFX = updateGFX

return M