-- 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 function setAllLightsEnabled(group, value)
  for i = 0, group:size() - 1 do
    local obj = Sim.upcast(group.obj:at(i))
    if obj then
      if obj.obj:isSubClassOf('LightBase') then
        obj.obj:setLightEnabled(value)
      end
      if obj:getClassName() == 'Prefab' then
        setAllLightsEnabled(obj, value)
      end
    end
  end
end

local lastValue = nil
local lastValue_burners = nil

local function onUpdate()
  local tod = scenetree.tod
  if not tod then return end

  local value = false
  if tod.time > 0.21 and tod.time < 0.79 then
    value = true
  end

  if lastValue == value then return end
  lastValue = value

  if scenetree.dynamic_lights then
    setAllLightsEnabled(scenetree.dynamic_lights, value ,"")
  end

  local value_burners = false
  if tod.time > 0.18 and tod.time < 0.82 then
    value_burners = true
  end

  if lastValue_burners == value_burners then return end
  lastValue_burners = value_burners

  if scenetree.burners_lights then
    setAllLightsEnabled(scenetree.burners_lights, value_burners ,"")
  end
end

M.onUpdate = onUpdate

return M