local LD = require("design.LevelDesignLibrary")
local timers = require("level.timer")
local uiCalls = require("ui.uicalls")
local thisLevel, player, son, resetRandom_CooldownTimer
local TutorialBanterPlayed = false
local Debug_RerollWadsMonitor, Debug_SimpleFightsMonitor
local currentMist_Count = 0
local initialMist_Count = 0
local displayMistCounter = false
local displayMistCounter_Dec = 0
local CurseWarning_01_Enabled = false
local CurseWarning_02_Enabled = false
local AreaUIDisplayed = false
local Debug_CurseBlightMonitor, Debug_NextAISetMonitor, Debug_SetTrapLayout_Monitor, Debug_SetTrapVariant_Monitor
local debug_enableMonitors = false
local VariantSelection = 1
local LayoutSelection = 1
local LayoutVariantCount = {
  14,
  20,
  8,
  12,
  8,
  12
}
local Area_Entrance = {
  Wad = "Nid100_Entrance",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 1,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_SWHall = {
  Wad = "Nid200_SWHallway",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 0,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_WRoom = {
  Wad = "Nid300_WRoom",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 2,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_NWHall = {
  Wad = "Nid220_NWHallway",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 0,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_NWRoom = {
  Wad = "Nid310_NWRoom",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 3,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_NRoom = {
  Wad = "Nid320_NRoom",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 2,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_NERoom = {
  Wad = "Nid330_NERoom",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 3,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_NEHall = {
  Wad = "Nid240_NEHallway",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 0,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_ERoom = {
  Wad = "Nid340_ERoom",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 2,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Area_SEHall = {
  Wad = "Nid260_SEHallway",
  Deadend = false,
  RuneRead = false,
  TripleChest = false,
  EncounterType = 0,
  RepopulateSetup = true,
  deliveringInfo = "--"
}
local Possible_Areas = {
  Area_Entrance,
  Area_SWHall,
  Area_WRoom,
  Area_NWHall,
  Area_NWRoom,
  Area_NRoom,
  Area_NERoom,
  Area_NEHall,
  Area_ERoom,
  Area_SEHall
}
local Loaded_WADs = {
  Nid100_Entrance = {},
  Nid200_SWHallway = {},
  Nid300_WRoom = {},
  Nid220_NWHallway = {},
  Nid310_NWRoom = {},
  Nid320_NRoom = {},
  Nid330_NERoom = {},
  Nid240_NEHallway = {},
  Nid340_ERoom = {},
  Nid260_SEHallway = {}
}
local Possible_TripleChestSetups_01 = {
  "Nid200_SWHallway",
  "Nid260_SEHallway",
  "Nid220_NWHallway",
  "Nid240_NEHallway",
  "Nid220_NWHallway",
  "Nid240_NEHallway"
}
local Possible_Deadends = {
  "Nid200_SWHallway",
  "Nid220_NWHallway",
  "Nid240_NEHallway",
  "Nid260_SEHallway"
}
local SelectedAISet
local AISets = {
  "AI_1111",
  "AI_1121",
  "AI_1131",
  "AI_1211",
  "AI_1221",
  "AI_1231",
  "AI_1311",
  "AI_1321",
  "AI_1331",
  "AI_2111",
  "AI_2121",
  "AI_2131",
  "AI_2211",
  "AI_2221",
  "AI_2231",
  "AI_2311",
  "AI_2321",
  "AI_2331",
  "AI_3111",
  "AI_3121",
  "AI_3131",
  "AI_3211",
  "AI_3221",
  "AI_3231",
  "AI_3311",
  "AI_3321",
  "AI_3331",
  "AI_1112",
  "AI_1122",
  "AI_1132",
  "AI_1212",
  "AI_1222",
  "AI_1232",
  "AI_1312",
  "AI_1322",
  "AI_1332",
  "AI_2112",
  "AI_2122",
  "AI_2132",
  "AI_2212",
  "AI_2222",
  "AI_2232",
  "AI_2312",
  "AI_2322",
  "AI_2332",
  "AI_3112",
  "AI_3122",
  "AI_3132",
  "AI_3212",
  "AI_3222",
  "AI_3232",
  "AI_3312",
  "AI_3322",
  "AI_3332",
  "AI_1123",
  "AI_1133",
  "AI_1213",
  "AI_1223",
  "AI_1233",
  "AI_1313",
  "AI_1323",
  "AI_1333",
  "AI_2123",
  "AI_2133",
  "AI_2213",
  "AI_2223",
  "AI_2233",
  "AI_2313",
  "AI_2323",
  "AI_2333",
  "AI_3123",
  "AI_3133",
  "AI_3213",
  "AI_3223",
  "AI_3233",
  "AI_3313",
  "AI_3323",
  "AI_3333"
}
local wadManagerList = {}
local warningMusic = false
local DEBUG_ENABLE_MONITORS = engine.VFSBool.New("Debug Enable Monitors")
function OnScriptLoaded(level)
  thisLevel = level
  player = game.Player.FindPlayer()
  son = game.AI.FindSon()
  SelectedAISet = game.Level.GetVariable("NIF_SelectedAIMix")
end
function OnStart(level)
  CurseWarning_01_Enabled = false
  CurseWarning_02_Enabled = false
  displayMistCounter = false
  initialMist_Count = 0
  for i = 1, #Possible_Areas do
    local wadName = Possible_Areas[i].Wad
    Loaded_WADs[wadName] = {
      level = game.FindLevel(wadName),
      index = i
    }
    if Loaded_WADs[wadName].level then
      wadManagerList[wadName] = Loaded_WADs[wadName].level:GetGameObject("WadManager_root")
    end
  end
  if LD.GetEntityVariable("NIF_ValkyrieDefeated") == false and game.Wallets.GetResourceValue("HERO", "ValkyrieLoot07") ~= -1 then
    LD.SetEntityVariable("NIF_ValkyrieDefeated", true)
    local valkyriesDefeated = game.Level.GetVariable("ValkyriesDefeated")
    valkyriesDefeated = valkyriesDefeated + 1
    game.Level.SetVariable("ValkyriesDefeated", valkyriesDefeated)
    if LD.GetEntityVariable("NIF_ValkyrieChest") == true or LD.GetEntityVariable("NIF_ValkyrieWeapon") == true or LD.GetEntityVariable("NIF_ValkyrieEnchantment") == true then
      if LD.GetEntityVariable("NIF_ValkyrieChest") == true and 0 < game.Wallets.GetResourceValue("LOST_ITEMS", "KratosArmorChest_ValkyrieSet_Tier06") then
        game.Wallets.AddResource("HERO", "KratosArmorChest_ValkyrieSet_Tier06", 1, "NO_TELEMETRY", "", true)
        game.Wallets.AddRecipe("HERO", "Recipe_KratosArmorChest_ValkyrieSet_Tier06_Reinforcement_1")
        game.Wallets.RemoveResource("LOST_ITEMS", "KratosArmorChest_ValkyrieSet_Tier06", 1)
        game.Wallets.RemoveRecipe("LOST_ITEMS", "Recipe_KratosArmorChest_ValkyrieSet_Tier06_Reinforcement_1", 1)
      end
      if LD.GetEntityVariable("NIF_ValkyrieWeapon") == true and 0 < game.Wallets.GetResourceValue("LOST_ITEMS", "WeaponComponent_Axe_Valkyrie02") then
        game.Wallets.AddResource("HERO", "WeaponComponent_Axe_Valkyrie02", 1, "NO_TELEMETRY", "", true)
        game.Wallets.AddRecipe("HERO", "Recipe_WeaponComponent_Axe_Valkyrie02_Tier05_Reinforce_1")
        game.Wallets.RemoveResource("LOST_ITEMS", "WeaponComponent_Axe_Valkyrie02", 1)
        game.Wallets.RemoveRecipe("LOST_ITEMS", "Recipe_WeaponComponent_Axe_Valkyrie02_Tier05_Reinforce_1", 1)
      end
      if LD.GetEntityVariable("NIF_ValkyrieEnchantment") == true and game.Wallets.GetRunesWithFlags("LOST_ITEMS", {
        "RuneCreator_Unique_Valkyrie01"
      }) ~= nil == true then
        local result = game.Wallets.GetRunesWithFlags("LOST_ITEMS", {
          "RuneCreator_Unique_Valkyrie01"
        })
        for _, runeId in ipairs(result) do
          game.Wallets.ExchangeRune("HERO", "LOST_ITEMS", runeId)
        end
      end
      if 1 <= game.Wallets.GetResourceValue("LOST_ITEMS", "AsgardianSteel") then
        game.Wallets.AddResource("HERO", "AsgardianSteel", 1, "NO_TELEMETRY", "", true)
        game.Wallets.RemoveResource("LOST_ITEMS", "AsgardianSteel", 1)
      end
      if 1 <= game.Wallets.GetResourceValue("LOST_ITEMS", "AsgardianSteel") then
        game.Wallets.AddResource("HERO", "AsgardianSteel", 1, "NO_TELEMETRY", "", true)
        game.Wallets.RemoveResource("LOST_ITEMS", "AsgardianSteel", 1)
      end
      if game.Wallets.GetResourceValue("HERO", "ValkyriesKilled") >= 5 and 1 <= game.Wallets.GetResourceValue("LOST_ITEMS", "PerfectAsgardianSteel") then
        game.Wallets.AddResource("HERO", "PerfectAsgardianSteel", 1, "NO_TELEMETRY", "", true)
        game.Wallets.RemoveResource("LOST_ITEMS", "PerfectAsgardianSteel", 1)
      end
      if 0 < game.Wallets.GetResourceValue("LOST_ITEMS", "NiflheimRareLootD") then
        game.Wallets.AddResource("HERO", "NiflheimRareLootD", 1, "NO_TELEMETRY", "", true)
        game.Wallets.RemoveResource("LOST_ITEMS", "NiflheimRareLootD", 1)
      end
    end
  end
  HideCubbyHelperZones()
end
function CompleteArrivalQuest()
  if AreaUIDisplayed == false then
    AreaUIDisplayed = true
    uiCalls.UI_Event_DiscoverLocation("NiflheimMain")
    LD.CompleteQuest("Quest_SonLanguage_Niflheim_Travel")
  end
end
function Set_AreaUIDisplayed_True()
  AreaUIDisplayed = true
end
function OnWadLoaded(level, newLevel)
  local wadKey = string.sub(newLevel.Name, 5)
  if Loaded_WADs[wadKey] then
    Loaded_WADs[wadKey].level = newLevel
    DeliverWadInfo(Loaded_WADs[wadKey].index)
    wadManagerList[wadKey] = newLevel:GetGameObject("WadManager_root")
  end
end
function OnWadUnloaded(level, newLevel)
  local wadKey = string.sub(newLevel.Name, 5)
  if Loaded_WADs[wadKey] then
    Loaded_WADs[wadKey].level = nil
    wadManagerList[wadKey] = nil
  end
end
local Debug_InitalizeMonitors = function()
  if DEBUG_ENABLE_MONITORS.value == false then
    return
  end
  if engine.IsDebug() and debug_enableMonitors == false then
    debug_enableMonitors = true
    local monitors = require("level.MonitorLibrary")
    Debug_RerollWadsMonitor = monitors.CreateEntityVariableMonitor("Debug_RerollRandom")
    Debug_RerollWadsMonitor:OnValue(true, ResetRandom)
    Debug_RerollWadsMonitor:SetPrintsEnabled(false)
    Debug_SimpleFightsMonitor = monitors.CreateEntityVariableMonitor("Debug_SimpleFights")
    Debug_SimpleFightsMonitor:OnVariableChange(Debug_SimpleFights)
    Debug_SimpleFightsMonitor:SetPrintsEnabled(false)
    Debug_CurseBlightMonitor = monitors.CreateEntityVariableMonitor("Debug_Disable_CurseFog")
    Debug_CurseBlightMonitor:OnValue(true, DisableBlight)
    Debug_CurseBlightMonitor:SetPrintsEnabled(false)
    Debug_NextAISetMonitor = monitors.CreateEntityVariableMonitor("Debug_Next_AIMix")
    Debug_NextAISetMonitor:OnValue(true, Debug_NextAISet)
    Debug_NextAISetMonitor:SetPrintsEnabled(false)
    Debug_SetTrapVariant_Monitor = monitors.CreateEntityVariableMonitor("Debug_Set_TrapVariant")
    Debug_SetTrapVariant_Monitor:OnVariableChange(Debug_Set_NextVarient)
    Debug_SetTrapVariant_Monitor:SetPrintsEnabled(false)
    Debug_SetTrapLayout_Monitor = monitors.CreateEntityVariableMonitor("Debug_Set_TrapLayout")
    Debug_SetTrapLayout_Monitor:OnVariableChange(Debug_Set_NextLayout)
    Debug_SetTrapLayout_Monitor:SetPrintsEnabled(false)
  end
end
function OnUpdate(level)
  DebugGetWadInfo()
  Debug_WadMangers()
  Debug_InitalizeMonitors()
  if CurseWarning_01_Enabled == true and tonumber(player:MeterGetValue("NiflheimBlightProtection")) < 90 and tonumber(player:MeterGetValue("NiflheimBlightProtection")) > 0 then
    CurseWarning_01_Enabled = false
    local WarningBanter = "Nifl_CurseWarning_0" .. tostring(math.random(1, 7))
    game.Audio.PlayBanterNonCritical(WarningBanter)
  end
  if CurseWarning_02_Enabled == true and tonumber(player:MeterGetValue("NiflheimBlightProtection")) < 50 and tonumber(player:MeterGetValue("NiflheimBlightProtection")) > 0 then
    CurseWarning_02_Enabled = false
    local WarningBanter = "Nifl_CurseWarning_0" .. tostring(math.random(1, 7))
    game.Audio.PlayBanterNonCritical(WarningBanter)
  end
  if displayMistCounter == true then
    local currentMist_Target = game.Wallets.GetResourceValue("HERO", "NiflheimCurrency") - initialMist_Count
    if currentMist_Target > currentMist_Count then
      if displayMistCounter_Dec == 0 then
        local countDif = currentMist_Target - currentMist_Count
        displayMistCounter_Dec = math.floor((countDif + 59) / 60)
      end
      currentMist_Count = currentMist_Count + displayMistCounter_Dec
      if currentMist_Target < currentMist_Count then
        currentMist_Count = currentMist_Target
      end
    elseif displayMistCounter_Dec ~= 0 then
      displayMistCounter_Dec = 0
    end
    if 0 < game.Wallets.GetResourceValue("HERO", "NiflheimCurrency") and 0 < currentMist_Count then
      uiCalls.EnableMechanicText("[MSG: 10955]: " .. tostring(currentMist_Count))
    end
  end
end
function HideMistDisplay()
  displayMistCounter = false
  uiCalls.DisableMechanicText()
  if 0 < currentMist_Count then
    if player:IsDead() == false and player:IsDying() == false then
      local currentMist_Target = game.Wallets.GetResourceValue("HERO", "NiflheimCurrency") - initialMist_Count
      uiCalls.SendBottomDesignerMessage({
        Text = 44100,
        formattedArgs = {currentMist_Target},
        DisplayTime = 5,
        Critical = true
      })
    else
      uiCalls.SendBottomDesignerMessage({
        Text = 44100,
        formattedArgs = {0},
        DisplayTime = 5,
        Critical = true
      })
    end
  end
end
function StartMistCountDisplay()
  if game.Wallets.GetResourceValue("HERO", "NiflheimCurrency") > 0 then
    initialMist_Count = game.Wallets.GetResourceValue("HERO", "NiflheimCurrency")
  else
    initialMist_Count = 0
  end
  currentMist_Count = 0
  displayMistCounter = true
end
function OnSaveCheckpoint(level)
  return {TutorialBanterPlayed = TutorialBanterPlayed}
end
function OnRestoreCheckpoint(level, savedInfo)
  TutorialBanterPlayed = savedInfo.TutorialBanterPlayed or false
end
function ResetEnounters(wads)
end
function ResetEnounters_onloaded(wads)
end
function DisplayTutorial()
  buttonMusic()
  if TutorialBanterPlayed == false then
    game.Audio.PlayBanterNonCritical("Nifl_MazeEntrance_Statue")
  end
  GameObjects.sonreadrune_Repeat:FindSingleGOByName("GenericSonInteract").LuaObjectScript.Disable()
  local textToDisplay = [=[
[MSG: 37303]
[MSG: 37304]
[MSG: 37305]]=]
  uiCalls.SendSplashScreenDesignerMessage({
    Text = textToDisplay,
    Title = 37302,
    CompletionHook = {
      LevelName = "Nid000_LevelGlobal",
      HookName = "PlayTutorialBanter"
    },
    AdvanceType = uiCalls.msgParam.ADVANCE_PRESS,
    ImageMaterialName = "nifmaze",
    Critical = true
  })
  LD.CallFunctionAfterDelay(EnableTutorial, 10)
end
function PlayTutorialBanter()
  if TutorialBanterPlayed == false then
    TutorialBanterPlayed = true
    game.Audio.PlayBanterNonCritical("Nifl_MazeEntrance_StatueExit")
  end
end
function EnableTutorial()
  GameObjects.sonreadrune_Repeat:FindSingleGOByName("GenericSonInteract").LuaObjectScript.Enable()
end
function EnterBehaviorContext_WAIT_AND_EXPLORE()
  son:CallScript("EnterBehaviorContext", "WAIT_AND_EXPLORE_BEHAVIOR_CONTEXT_CONFIG")
end
function EnterBehaviorContext_NEARPOISON()
  son:CallScript("EnterBehaviorContext", "SICK_BEHAVIOR_CONTEXT_CONFIG")
end
function ClearBehaviorContext()
  son:CallScript("ClearBehaviorContext")
end
function EnableBlight()
  if LD.GetEntityVariable("Debug_Disable_CurseFog") == false then
    player:CallScript("LuaHook_NiflheimBlightStart")
    uiCalls.EnableMechanicMeter("NiflheimBlightProtection", true)
    CurseWarning_01_Enabled = true
    CurseWarning_02_Enabled = true
  end
  game.World.DisableSoftSave()
  game.World.DisablePlayerStateSoftSave()
  game.Compass.SetDesignerForcedHide(true)
end
function DisableBlight()
  if LD.GetEntityVariable("Debug_Disable_CurseFog") == false then
    player:CallScript("LuaHook_NiflheimBlightEnd")
    CurseWarning_01_Enabled = false
    CurseWarning_02_Enabled = false
    if player:IsDead() == false and player:IsDying() == false then
      player:MeterSetValue("Health", player:MeterGetMax("Health"))
      uiCalls.DisableMechanicMeter()
    end
  end
  game.World.EnableSoftSave()
  game.World.EnablePlayerStateSoftSave()
  game.Compass.SetDesignerForcedHide(false)
end
function Enable_JustTheBlight()
  if LD.GetEntityVariable("Debug_Disable_CurseFog") == false then
    player:CallScript("LuaHook_NiflheimBlightStart")
    uiCalls.EnableMechanicMeter("NiflheimBlightProtection", true)
  end
end
function Disable_JustTheBlight()
  if LD.GetEntityVariable("Debug_Disable_CurseFog") == false then
    player:CallScript("LuaHook_NiflheimBlightEnd")
    uiCalls.DisableMechanicMeter()
  end
end
function Convert_WadName_To_PossibleAreaIndex(wadName)
  local possibleWads = {
    Nid100_Entrance = 1,
    Nid200_SWHallway = 2,
    Nid300_WRoom = 3,
    Nid220_NWHallway = 4,
    Nid310_NWRoom = 5,
    Nid320_NRoom = 6,
    Nid330_NERoom = 7,
    Nid240_NEHallway = 8,
    Nid340_ERoom = 9,
    Nid260_SEHallway = 10
  }
  return possibleWads[wadName]
end
function GetWadInfo(level, askingWad)
  if Loaded_WADs[askingWad] then
    if Loaded_WADs[askingWad].level then
      DeliverWadInfo(Loaded_WADs[askingWad].index)
      Possible_Areas[Loaded_WADs[askingWad].index].deliveringInfo = "progress"
    end
  else
    engine.Error("WAD " .. askingWad .. " does not have an entry in Possible Areas")
  end
end
function DeliverWadInfo(i)
  local Wad = Loaded_WADs[Possible_Areas[i].Wad].level
  if Wad then
    local WadManager = Wad:GetGameObject("WadManager_root")
    WadManager:CallScript("UpdateWad", Possible_Areas[i], thisLevel)
    Possible_Areas[i].deliveringInfo = "CallScript"
  end
end
function DeliverWadInfoComplete(level, updatedArea)
  if Loaded_WADs[updatedArea.Wad] then
    Possible_Areas[Loaded_WADs[updatedArea.Wad].index] = updatedArea
    Possible_Areas[Loaded_WADs[updatedArea.Wad].index].deliveringInfo = "Complete"
  end
end
function resetAreas()
  for i = 1, #Possible_Areas do
    print("Resetting Areas")
    Possible_Areas[i].Deadend = false
    Possible_Areas[i].RuneRead = false
    Possible_Areas[i].TripleChest = false
    Possible_Areas[i].RepopulateSetup = true
    Possible_Areas[i].deliveringInfo = "resetAreas"
  end
  game.EvaluateLoadZones()
end
function rerollAreas()
  local triple_index1 = Convert_WadName_To_PossibleAreaIndex(Possible_TripleChestSetups_01[math.random(1, #Possible_TripleChestSetups_01)])
  Possible_Areas[triple_index1].TripleChest = true
  SelectedAISet = math.random(1, #AISets)
  game.Level.SetVariable("NIF_SelectedAIMix", SelectedAISet)
end
function rerollAreas_lite()
  local triple_index1 = Convert_WadName_To_PossibleAreaIndex(Possible_TripleChestSetups_01[math.random(1, #Possible_TripleChestSetups_01)])
  Possible_Areas[triple_index1].TripleChest = true
  SelectedAISet = game.Level.GetVariable("NIF_SelectedAIMix")
end
function Debug_NextAISet()
  if SelectedAISet < #AISets then
    SelectedAISet = SelectedAISet + 1
  else
    SelectedAISet = 1
  end
  game.Level.SetVariable("NIF_SelectedAIMix", SelectedAISet)
  game.EvaluateLoadZones()
  for i = 1, #Possible_Areas do
    DeliverWadInfo(i)
  end
  uiCalls.UI_Event_TurnOffDesignerMessage()
  uiCalls.UI_Event_SendDesignerMessage("Next AI Set Selected: #" .. tostring(game.Level.GetVariable("NIF_SelectedAIMix")) .. "/" .. tostring(#AISets) .. " (" .. AISets[SelectedAISet] .. ")")
  print("Global Set to True")
  timers.StartLevelTimer(0.1, function()
    LD.SetEntityVariable("Debug_Next_AIMix", false)
  end)
end
function ResetRandom()
  if resetRandom_CooldownTimer == nil then
    resetAreas()
    rerollAreas()
    for i = 1, #Possible_Areas do
      DeliverWadInfo(i)
    end
    if LD.GetEntityVariable("NIF_BackFightThisTrip") == true then
      LD.SetEntityVariable("NIF_MemoryChestAvaiable", true)
      LD.SetEntityVariable("NIF_BackFightThisTrip", false)
    end
    if LD.GetEntityVariable("NIF_BackFightThisTrip") == true or LD.GetEntityVariable("NIF_MemoryChestAvaiable") == true then
      Loaded_WADs.Nid100_Entrance.level:CallScript("Randomize_MemoryChestRunes", true)
    else
      Loaded_WADs.Nid100_Entrance.level:CallScript("Randomize_MemoryChestRunes", false)
    end
    if game.Wallets.GetResourceValue("HERO", "NiflheimTierTracker") > 0 then
      print("Normal Reset")
      game.Wallets.RemoveResource("HERO", "NiflheimTierTracker", (game.Wallets.GetResourceValue("HERO", "NiflheimTierTracker")))
    end
    if engine.IsDebug() and LD.GetEntityVariable("Debug_RerollRandom") == true then
      LD.SetEntityVariable("Debug_RerollRandom", false)
    end
    local timers = require("level.timer")
    resetRandom_CooldownTimer = timers.StartLevelTimer(5, function()
      resetRandom_CooldownTimer:Stop()
      resetRandom_CooldownTimer = nil
    end)
  end
end
function ResetRandom_lite()
  if resetRandom_CooldownTimer == nil then
    resetAreas()
    rerollAreas_lite()
    for i = 1, #Possible_Areas do
      DeliverWadInfo(i)
    end
    if LD.GetEntityVariable("NIF_BackFightThisTrip") == true then
      LD.SetEntityVariable("NIF_MemoryChestAvaiable", true)
      LD.SetEntityVariable("NIF_BackFightThisTrip", false)
    end
    if LD.GetEntityVariable("NIF_BackFightThisTrip") == true or LD.GetEntityVariable("NIF_MemoryChestAvaiable") == true then
      Loaded_WADs.Nid100_Entrance.level:CallScript("Randomize_MemoryChestRunes", true)
    else
      Loaded_WADs.Nid100_Entrance.level:CallScript("Randomize_MemoryChestRunes", false)
    end
    if game.Wallets.GetResourceValue("HERO", "NiflheimTierTracker") > 0 then
      print("Lite Reset")
      game.Wallets.RemoveResource("HERO", "NiflheimTierTracker", (game.Wallets.GetResourceValue("HERO", "NiflheimTierTracker")))
    end
    if engine.IsDebug() and LD.GetEntityVariable("Debug_RerollRandom") == true then
      LD.SetEntityVariable("Debug_RerollRandom", false)
    end
    local timers = require("level.timer")
    resetRandom_CooldownTimer = timers.StartLevelTimer(5, function()
      resetRandom_CooldownTimer:Stop()
      resetRandom_CooldownTimer = nil
    end)
  end
end
function PopulateEncounters()
  local Nid500Level = game.FindLevel("Nid500_MazeEncounters")
  if Nid500Level ~= nil then
    Nid500Level:GetGameObject("Nid100_EncounterManager").Child:CallScript("RollEncounter", Possible_Areas[1].EncounterType, SelectedAISet)
    Nid500Level:GetGameObject("Nid300_EncounterManager").Child:CallScript("RollEncounter", Possible_Areas[3].EncounterType, SelectedAISet)
    if game.Wallets.GetResourceValue("HERO", "ValkyrieLoot07") ~= -1 then
      Nid500Level:GetGameObject("Nid310_EncounterManager").Child:CallScript("RollEncounter", Possible_Areas[5].EncounterType, SelectedAISet)
    else
      Nid500Level:GetGameObject("Nid310_EncounterManager").Child:CallScript("RollEncounter", 0, SelectedAISet)
    end
    Nid500Level:GetGameObject("Nid320_EncounterManager").Child:CallScript("RollEncounter", Possible_Areas[6].EncounterType, SelectedAISet)
    Nid500Level:GetGameObject("Nid330_EncounterManager").Child:CallScript("RollEncounter", Possible_Areas[7].EncounterType, SelectedAISet)
    Nid500Level:GetGameObject("Nid340_EncounterManager").Child:CallScript("RollEncounter", Possible_Areas[9].EncounterType, SelectedAISet)
  end
end
function RezStones_Disable()
  player:CallScript("LuaHook_DisableRevive", true)
end
function RezStones_Enable()
  player:CallScript("LuaHook_DisableRevive", false)
end
function Debug_SimpleFights()
  LD.SetEntityVariable("NIF_SimpleFights", LD.GetEntityVariable("Debug_SimpleFights"))
end
function Debug_Set_NextVarient()
  if LD.GetEntityVariable("Debug_EnableTrapDebug") == true then
    VariantSelection = LD.GetEntityVariable("Debug_Set_TrapVariant")
    if VariantSelection > LayoutVariantCount[LayoutSelection] then
      VariantSelection = 1
      LD.SetEntityVariable("Debug_Set_TrapVariant", 1)
    elseif VariantSelection < 1 then
      VariantSelection = LayoutVariantCount[LayoutSelection]
      LD.SetEntityVariable("Debug_Set_TrapVariant", VariantSelection)
    end
    for i = 1, #Possible_Areas do
      DeliverWadInfo(i)
    end
    uiCalls.UI_Event_TurnOffDesignerMessage()
    if LayoutSelection ~= 7 then
      uiCalls.UI_Event_SendDesignerMessage("Trap Layout #" .. tostring(LayoutSelection) .. ", Variant #" .. tostring(VariantSelection) .. "/" .. tostring(LayoutVariantCount[LayoutSelection]))
    else
      uiCalls.UI_Event_SendDesignerMessage("Trap Layout #" .. tostring(LayoutSelection) .. "(Dead Ends), Variant #" .. tostring(VariantSelection) .. "/" .. tostring(LayoutVariantCount[LayoutSelection]))
    end
  else
    uiCalls.UI_Event_SendDesignerMessage("Set Enable Trap Debug to True to enable Debug Trap Testing")
  end
end
function Debug_Set_NextLayout()
  if LD.GetEntityVariable("Debug_EnableTrapDebug") == true then
    LayoutSelection = LD.GetEntityVariable("Debug_Set_TrapLayout")
    if LayoutSelection > #LayoutVariantCount then
      LayoutSelection = 1
      LD.SetEntityVariable("Debug_Set_TrapLayout", 1)
    elseif LayoutSelection < 1 then
      LayoutSelection = #LayoutVariantCount
      LD.SetEntityVariable("Debug_Set_TrapLayout", #LayoutVariantCount)
    end
    if VariantSelection > LayoutVariantCount[LayoutSelection] then
      VariantSelection = 1
      LD.SetEntityVariable("Debug_Set_TrapVariant", 1)
    end
    for i = 1, #Possible_Areas do
      DeliverWadInfo(i)
    end
    uiCalls.UI_Event_TurnOffDesignerMessage()
    if LayoutSelection ~= 7 then
      uiCalls.UI_Event_SendDesignerMessage("Trap Layout #" .. tostring(LayoutSelection) .. ", Variant #" .. tostring(VariantSelection) .. "/" .. tostring(LayoutVariantCount[LayoutSelection]))
    else
      uiCalls.UI_Event_SendDesignerMessage("Trap Layout #" .. tostring(LayoutSelection) .. "(Dead Ends), Variant #" .. tostring(VariantSelection) .. "/" .. tostring(LayoutVariantCount[LayoutSelection]))
    end
  else
    uiCalls.UI_Event_SendDesignerMessage("Set Enable Trap Debug to True to enable Debug Trap Testing")
  end
end
function DebugGetWadInfo()
  if engine.IsDebug() then
    local debugTable = {}
    debugTable.Title = "Nid000 WadInfo"
    debugTable.X = 75
    debugTable.Y = 10
    debugTable.TitleColor = engine.Vector.New(10, 0, 128)
    local showWadInfo = LD.GetEntityVariable("Debug_ShowWadInfo")
    local showTripleInfo = LD.GetEntityVariable("Debug_ShowChestInfo")
    local showTrapHallInfo = LD.GetEntityVariable("Debug_ShowTrapHall_Info")
    if showWadInfo == true then
      debugTable[#debugTable + 1] = {
        "Level Loaded",
        "WAD: ",
        "Reroll Setup",
        "EncounterType"
      }
      for i = 1, #Possible_Areas do
        local isWadLoaded = "Unloaded"
        if Loaded_WADs[Possible_Areas[i].Wad].level then
          isWadLoaded = "Loaded"
        end
        debugTable[#debugTable + 1] = {
          isWadLoaded,
          Possible_Areas[i].Wad,
          Possible_Areas[i].RepopulateSetup or "--",
          Possible_Areas[i].EncounterType or "None"
        }
      end
    end
    if showTrapHallInfo == true then
      debugTable[#debugTable + 1] = {
        "Level Loaded",
        "WAD: ",
        "TrapHall1 (Lay,Var)",
        "Treasures",
        "TrapHall2(Lay,Var)",
        "Treasures"
      }
      for i = 1, #Possible_Areas do
        local isWadLoaded = "Unloaded"
        if Loaded_WADs[Possible_Areas[i].Wad].level then
          isWadLoaded = "Loaded"
        end
        local trapHall = {nil, nil}
        local bonusChest = {nil, nil}
        if Possible_Areas[i].LayoutSelection and Possible_Areas[i].VariantSelection then
          for x = 1, #Possible_Areas[i].LayoutSelection do
            trapHall[x] = Possible_Areas[i].LayoutSelection[x] .. ", " .. Possible_Areas[i].VariantSelection[x]
            bonusChest[x] = Possible_Areas[i].BonusTreasure_Chest[x]
          end
        end
        debugTable[#debugTable + 1] = {
          isWadLoaded,
          Possible_Areas[i].Wad,
          trapHall[1] or "--",
          bonusChest[1] or "--",
          trapHall[2] or "--",
          bonusChest[2] or "--"
        }
      end
    end
    if showTripleInfo == true then
      debugTable[#debugTable + 1] = {
        "WAD: ",
        "ChestSetup",
        "TripleChestSetup",
        " Fake Target Location Names ",
        "",
        ""
      }
      for i = 1, #Possible_Areas do
        local chestsDebugString = ""
        if Possible_Areas[i].commonChest then
          chestsDebugString = chestsDebugString .. "Com,"
        end
        if Possible_Areas[i].coffin then
          chestsDebugString = chestsDebugString .. " Coff,"
        end
        if Possible_Areas[i].legendaryChest then
          chestsDebugString = chestsDebugString .. " Legd"
        end
        local debugTripleLocs = {
          "--",
          "--",
          "--"
        }
        if Possible_Areas[i].DebugTripleLocations then
          debugTripleLocs[1] = Possible_Areas[i].DebugTripleLocations[1]
          debugTripleLocs[2] = Possible_Areas[i].DebugTripleLocations[2]
          debugTripleLocs[3] = Possible_Areas[i].DebugTripleLocations[3]
        end
        local debugTriChest = "--"
        if Possible_Areas[i].TripleChest then
          debugTriChest = "Setup_"
          if Loaded_WADs[Possible_Areas[i].Wad].level then
            if Possible_Areas[i].TripleChestSelected then
              if wadManagerList[Possible_Areas[i].Wad] then
                wadManagerList[Possible_Areas[i].Wad]:CallScript("Debug_TripleChestText")
              end
              debugTriChest = debugTriChest .. "0 " .. tostring(Possible_Areas[i].TripleChestSelected) .. " = " .. (Possible_Areas[i].DebugKeyType or " ")
            else
              debugTriChest = debugTriChest .. "No_ChestSelected" .. " = " .. (Possible_Areas[i].DebugKeyType or " ")
            end
          else
            debugTriChest = debugTriChest .. "Unloaded"
          end
        end
        debugTable[#debugTable + 1] = {
          Possible_Areas[i].Wad,
          chestsDebugString or "--",
          debugTriChest,
          debugTripleLocs[1],
          debugTripleLocs[2],
          debugTripleLocs[3]
        }
      end
    end
    engine.DrawDebugTable(debugTable)
  end
end
function Debug_WadMangers()
  if engine.IsDebug() and LD.GetEntityVariable("Debug_ShowTrapHall_Text") == true then
    for i = 1, #Possible_Areas do
      if Possible_Areas[i].level then
        if wadManagerList[Possible_Areas[i].Wad] then
          wadManagerList[Possible_Areas[i].Wad]:CallScript("Debug_TrapHallInfo")
        else
          engine.Print("Nid000 Debug in Debug_WadMangers(): WadManager in " .. Possible_Areas[i].Wad .. " is nil")
        end
      end
    end
  end
end
function buttonMusic()
  if warningMusic == false then
    game.Audio.StartMusic("SND_MX_NIF_warning")
    warningMusic = true
  end
end
function HideCubbyHelperZones()
  GameObjects.South_CubbyWarpHelper:HideEntityVolume()
end
function ShowCubbyHelperZones()
  GameObjects.South_CubbyWarpHelper:ShowEntityVolume()
end
function KratosEnter_East()
  ShowCubbyHelperZones()
  LD.CallFunctionAfterDelay(function()
    if player:IsInsideEntityZone("East_CubbyWarpHelper") == true and son:IsInsideEntityZone("East_CubbyWarpHelper") == false then
      son:CallScript("WarpAndReset", GameObjects.EastWarpPoint:GetWorldPosition(), GameObjects.EastWarpPoint:GetWorldForward())
      ClearCubbies()
    end
  end, 5)
end
function KratosEnter_West()
  ShowCubbyHelperZones()
  LD.CallFunctionAfterDelay(function()
    if player:IsInsideEntityZone("West_CubbyWarpHelper") == true and son:IsInsideEntityZone("West_CubbyWarpHelper") == false then
      son:CallScript("WarpAndReset", GameObjects.WestWarpPoint:GetWorldPosition(), GameObjects.WestWarpPoint:GetWorldForward())
      ClearCubbies()
    end
  end, 5)
end
function KratosEnter_North()
  LD.CallFunctionAfterDelay(function()
    if player:IsInsideEntityZone("North_CubbyWarpHelper") == true and son:IsInsideEntityZone("North_CubbyWarpHelper") == false then
      son:CallScript("WarpAndReset", GameObjects.NorthWarpPoint:GetWorldPosition(), GameObjects.NorthWarpPoint:GetWorldForward())
      ClearCubbies()
    end
  end, 5)
end
function KratosEnter_NorthWest()
  LD.CallFunctionAfterDelay(function()
    if player:IsInsideEntityZone("NorthWest_CubbyWarpHelper") == true and son:IsInsideEntityZone("NorthWest_CubbyWarpHelper") == false then
      son:CallScript("WarpAndReset", GameObjects.NorthWestWarpPoint:GetWorldPosition(), GameObjects.NorthWestWarpPoint:GetWorldForward())
      ClearCubbies()
    end
  end, 5)
end
function KratosEnter_NorthEast()
  LD.CallFunctionAfterDelay(function()
    if player:IsInsideEntityZone("NorthEast_CubbyWarpHelper") == true and son:IsInsideEntityZone("NorthEast_CubbyWarpHelper") == false then
      son:CallScript("WarpAndReset", GameObjects.NorthEastWarpPoint:GetWorldPosition(), GameObjects.NorthEastWarpPoint:GetWorldForward())
      ClearCubbies()
    end
  end, 5)
end
function KratosEnter_South()
  LD.CallFunctionAfterDelay(function()
    if player:IsInsideEntityZone("South_CubbyWarpHelper") == true and son:IsInsideEntityZone("South_CubbyWarpHelper") == false then
      son:CallScript("WarpAndReset", GameObjects.SouthWarpPoint:GetWorldPosition(), GameObjects.SouthWarpPoint:GetWorldForward())
      ClearCubbies()
      HideCubbyHelperZones()
    end
  end, 5)
end
function ClearCubbies()
  GameObjects.NECubby_Manager.LuaObjectScript.ClearActiveHole()
  GameObjects.NWCubby_Manager.LuaObjectScript.ClearActiveHole()
  GameObjects.SECubby_Manager.LuaObjectScript.ClearActiveHole()
  GameObjects.SWCubby_Manager.LuaObjectScript.ClearActiveHole()
end
