-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt

local M = {}

local cargoDoorBeam = nil
local function onInit()
  --get cargo door beam
  cargoDoorBeam = nil
  if v.data.hydros ~= nil then
    for _, hydro in pairs(v.data.hydros) do
      local hydroBeam = v.data.beams[hydro.beamCID]
      local breakGroup = hydroBeam.breakGroup or ""
      if type(breakGroup) == "table" then breakGroup = "" end
      
      if hydro.inputSource == "cargodoor" and breakGroup == "cargoDoorTop" then
        cargoDoorBeam = hydroBeam
      end
    end
  end
  
  electrics.values['conditional__landinglights'] = 0
	electrics.values['glowmap__overspeed'] = 0
  electrics.values['glowmap__overweight'] = 0
  electrics.values['glowmap__decisionheight__passed'] = 0
  electrics.values['glowmap__decisionheight__near'] = 0
end

local function onReset()
	onInit()
end

local cargoDoorLockSoundPlayed = true
local function updateCargodoor(dt)
  if cargoDoorBeam == nil then return end
  if obj:beamIsBroken(cargoDoorBeam.cid) then return end 
  
  local cgblen = obj:getBeamLengthRefRatio(cargoDoorBeam.cid)
  -- if CLOSED
  if cgblen < 0.765 or cgblen > 0.995 then
    electrics.values["cargodoorsound"] = 0
    
    --play lock sound 
    if cgblen > 0.995 and not cargoDoorLockSoundPlayed then
      sounds.playSoundOnceAtNode("A380-800_doorclose", cargoDoorBeam.id1, 1.9)
      cargoDoorLockSoundPlayed = true
    end
  else
    --if CLOSING/OPENING
    if cgblen < 0.95 then cargoDoorLockSoundPlayed = false end
    electrics.values["cargodoorsound"] = 0.99 
  end
end

local function updateGFX(dt)
  local vel = vec3(obj:getVelocity()):length()
  
  --cargo door sounds
  updateCargodoor(dt)
  
  --landing lights
  local llval = electrics.values.highbeamsmooth or 0
  if llval > 0.8 then
    electrics.values['conditional__landinglights'] = 1
  else
    electrics.values['conditional__landinglights'] = 0
  end
  
  --roughly 500mph
  --AMMENDED 2018 : 410 MPH
  if vel >= 183.2  then
    electrics.values['glowmap__overspeed'] = 1
  else
    electrics.values['glowmap__overspeed'] = 0
  end
  
  --weight sensor
  local wsval = electrics.values.weightsensor or 0
  if wsval >= 20000 then
    electrics.values['glowmap__overweight'] = 1
  else
    electrics.values['glowmap__overweight'] = 0
  end
  
  --cockpit alarms
  electrics.values["overspeedalarm"] = electrics.values['glowmap__overspeed'] * 0.99
  
  --stall alarm
  local frontBroken = (electrics.values.frontbroken or 0) > 0
  if not frontBroken then
    if vel <= 48.5 and vel > 2.2352 and electrics.values['vsi_feetPerMinute'] < -1500 then
      electrics.values["stallalarm"] = 0.99
    else
      electrics.values["stallalarm"] = 0
    end
  else
    electrics.values["stallalarm"] = 0
  end
  
end

-- public interface
M.onInit      = onInit
M.onReset     = onReset
M.updateGFX = updateGFX

return M