local LD = require("design.LevelDesignLibrary")
local timers = require("level.timer")
local monitors = require("level.MonitorLibrary")
local thisObj, EndCap_01, EndCap_02, EndCap_03, EndCap_04
local EndCaps = {}
local RerollMonitor
local saveDataTable = {}
function OnScriptLoaded(level, obj)
  thisObj = obj
  EndCap_01 = obj:FindSingleGOByName("EndCap_01")
  EndCap_02 = obj:FindSingleGOByName("EndCap_02")
  EndCap_03 = obj:FindSingleGOByName("EndCap_03")
  EndCap_04 = obj:FindSingleGOByName("EndCap_04")
  if thisObj:FindLuaTableAttribute("Stones_01") == true then
    table.insert(EndCaps, EndCap_01)
  else
    EndCap_01:Hide()
  end
  if thisObj:FindLuaTableAttribute("Statue_01") == true then
    table.insert(EndCaps, EndCap_02)
  else
    EndCap_02:Hide()
  end
  if thisObj:FindLuaTableAttribute("Statue_02") == true then
    table.insert(EndCaps, EndCap_03)
  else
    EndCap_03:Hide()
  end
  if thisObj:FindLuaTableAttribute("Pillar_01") == true then
    table.insert(EndCaps, EndCap_04)
  else
    EndCap_04:Hide()
  end
  RerollMonitor = monitors.CreateEntityVariableMonitor("NIF_RerollRandom")
  RerollMonitor:OnValue(true, SelectEndCap)
  game.SubObject.Sleep(obj)
  game.SubObject.SetForgetOnCheckpoint(obj)
end
function OnStart()
  if thisObj:FindLuaTableAttribute("isManaged") == false then
    SelectEndCap()
  end
  if thisObj:FindLuaTableAttribute("TestCycle") == true then
    timers.StartLevelTimer(5, SelectEndCap)
  end
end
function OnSaveCheckpoint(level, obj)
  return {saveDataTable = saveDataTable}
end
function OnRestoreCheckpoint(level, obj, savedInfo)
  saveDataTable = savedInfo.saveDataTable
  HideEndCaps()
  EndCaps[saveDataTable.scratch]:Show()
end
function HideEndCaps()
  for i = 1, #EndCaps do
    EndCaps[i]:Hide()
  end
end
function SelectEndCap()
  HideEndCaps()
  saveDataTable.scratch = math.random(1, #EndCaps)
  EndCaps[saveDataTable.scratch]:Show()
  if thisObj:FindLuaTableAttribute("TestCycle") == true then
    timers.StartLevelTimer(5, SelectEndCap)
  end
end
