local LD = require("design.LevelDesignLibrary")
local timer = require("level.timer")
local EC = require("design.Encounter")
local monitors = require("level.MonitorLibrary")
local TUT = require("game.GlobalTutorials")
local uiCalls = require("ui.uicalls")
local checkpoint = require("level.checkpoint")
local Player, son, thisLevel, BackAttackTrainingEncounter, ZoneSpawnMonitor, SpawnZone, chestOpen, bookmarkSaved, weaponSpecialTimer, specialsMessageOn, Area_1_Encounter_1, Area_1_Encounter_2
ZM_A1_E1_Attack = nil
function OnScriptLoaded(level)
  Player = game.Player.FindPlayer()
  son = game.AI.FindSon()
  thisLevel = level
  SpawnZone = level:GetGameObject("EntZn_Spawn")
  ZoneSpawnMonitor = monitors.CreateEntityZoneMonitor(Player, SpawnZone)
  ZoneSpawnMonitor:OnEnter(SpawnEncounter)
  ZoneSpawnMonitor:Stop()
  Helwalker_Area_1_Fight_1()
end
function OnStart(level, obj)
  GameObjects.DeathPlane:Hide()
  print("chestOpen ", chestOpen)
  if chestOpen then
    SetSonOccupied()
    timer.StartLevelTimer(4, SetupSequence)
  end
end
function EnableChestCA()
  if not chestOpen then
    GameObjects.CA_FoundChest.LuaObjectScript.Enable()
  end
end
function Helwalker_Area_1_Fight_1()
  Area_1_Encounter_1 = EC.NewEncounter(thisLevel, "[Area 1]EC:1 Intro Riv100", {
    CheckpointOnComplete = true,
    CheckpointOverrideObject = GameObjects.CheckpointOverride,
    StopMusic = "SND_MX_RIV_fight_2_out"
  })
  Area_1_Encounter_1:AddWave({
    {
      spawners = "HelWalker_N_SSA",
      spawnLocators = "A1_O_Loc_3",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0.382
    }
  })
  Area_1_Encounter_1:OnComplete(function()
    GameObjects.Riv100_Banter.LuaObjectScript.PostSecondFight_Banter()
    EnableChestCA()
    LTW_Update_ToPillar()
    son:CallScript("LuaHook_ToggleSlowdownStops", true)
    GameObjects.ca_combat_turret_01.LuaObjectScript.Disable()
    GameObjects.ca_combat_turret_02.LuaObjectScript.Disable()
    LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Hel_Walker")
  end)
  Area_1_Encounter_1:SetStartZone(thisLevel:GetGameObject("EntZn_Area_1_Spawn"))
  Area_1_Encounter_1:OnEnemyDeath(function()
    Area_1_Encounter_1:AlertEnemies()
  end)
  ZM_A1_E1_Attack = monitors.CreateEntityZoneMonitor(Player, thisLevel:GetGameObject("EntZn_Alert"))
  ZM_A1_E1_Attack:OnEnter(HellwalkerTriggered)
  ZM_A1_E1_Attack:SetTriggerCountLimit(1)
  ZM_A1_E1_Attack:MarkForSave()
end
function HellwalkerTriggered()
  GameObjects.DeathPlane:Show()
  GameObjects.EnvEvent_Hellwalker.LuaObjectScript.Trigger()
  Area_1_Encounter_1:StartWave()
  Area_1_Encounter_1:AlertEnemies()
end
function Area_1_Fight_2()
  GameObjects.EntZn_Area_1_AttackZone:HideEntityVolume()
  Area_1_Encounter_2 = EC.NewEncounter(thisLevel, "[Area 1]EC:2 Intro Riv100")
  Area_1_Encounter_2:AddWave({
    {
      spawners = "Draugr_N_SOHSE",
      spawnLocators = "A1_O_Loc_2",
      spawnWad = "Riv085_DangersEntranceLH",
      useSpawnLocatorsOnly = true,
      maxActive = 2,
      totalSpawns = 2,
      spawnCooldown = 1.3
    }
  })
  Area_1_Encounter_2:SetStartZone(thisLevel:GetGameObject("EntZn_Area_1_AttackZone"))
end
function _Patrol_Draugrs_Area_1_Fight_1()
  Area_1_Encounter_1 = EC.NewEncounter(thisLevel, "[Area 1]EC:1 Intro Riv00", {
    CheckpointOnComplete = true,
    CheckpointOverrideObject = GameObjects.CheckpointOverride.Child
  })
  Area_1_Encounter_1:AddWave({
    {
      spawners = "Draugr_L_Patrol_01",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0.282
    },
    {
      spawners = "Draugr_L_SUA",
      spawnLocators = "A1_O_Loc_2",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0.382
    }
  })
  Area_1_Encounter_1:OnComplete(function()
    GameObjects.Riv100_Banter.LuaObjectScript.PostSecondFight_Banter()
    son:CallScript("LuaHook_ToggleSlowdownStops", true)
    GameObjects.ca_combat_turret_01.LuaObjectScript.Disable()
    GameObjects.ca_combat_turret_02.LuaObjectScript.Disable()
  end)
  Area_1_Encounter_1:SetStartZone(thisLevel:GetGameObject("EntZn_Area_1_Spawn"))
  Area_1_Encounter_1:OnEnemyDeath(function()
    Area_1_Encounter_1:AlertEnemies()
  end)
  ZM_A1_E1_Attack = monitors.CreateEntityZoneMonitor(Player, thisLevel:GetGameObject("EntZn_Alert"))
  ZM_A1_E1_Attack:OnEnter(function()
    Area_1_Encounter_1:AlertEnemies()
  end)
  ZM_A1_E1_Attack:OnExit(function()
    Area_1_Encounter_1:AlertEnemies()
  end)
  ZM_A1_E1_Attack:SetTriggerCountLimit(1)
end
function CrackClimb_ExitBottom()
  local riv085 = game.FindLevel("Riv085_DangersEntranceLH")
  if riv085 ~= nil then
    riv085:CallScript("CA_StartPhase3")
  end
  CA_DisableIntro()
  GameObjects.CA_SyncExit_Bottom.LuaObjectScript.Enable()
end
function CrackClimb_ExitTop()
  LD.CallFunctionAfterDelay(RiverPass_Obj050, 2)
  local riv085 = game.FindLevel("Riv085_DangersEntranceLH")
  if riv085 ~= nil then
    riv085:CallScript("DisableContextActions")
  end
  son:CallScript("LuaHook_ToggleSlowdownStops", false)
  CA_EnableIntro()
  LD.CallFunctionAfterDelay(SaveBookmark, 2.5)
end
function RiverPass_Obj050()
  LD.CompleteQuest("Quest_RiverPass_Objective050")
end
function SaveBookmark()
  if not bookmarkSaved then
    bookmarkSaved = true
    local bookmarks = require("design.Bookmarks")
    local tableEntry = bookmarks["BOOKMARK_" .. "02_RiverPass_013_FightComplete"]
    tableEntry.OverrideObject = GameObjects.CheckpointOvr_FightComplete
    game.World.StoreCheckpointAndBookmark(tableEntry)
  end
end
function SpawnEncounter()
  BackAttackTrainingEncounter:Start()
  ZoneSpawnMonitor:Stop()
end
function StartEncounter()
end
function CA_DisablePreRuneRead()
  GameObjects.CA_ObserveForward_01.LuaObjectScript:Disable()
end
function ChestOpenStart()
  if game.GetNewGamePlus() then
    return
  end
  GameObjects.CA_RunicIdle.LuaObjectScript.Enable()
  SetSonOccupied()
end
function ChestOpenedFinish()
  GameObjects.CA_FoundChest.LuaObjectScript.Disable()
  GameObjects.EntZn_Area_1_AttackZone:ShowEntityVolume()
  GameObjects.EntZn_CheckSonOccupied:HideEntityVolume()
  GameObjects.CA_Area1_LiftGate.LuaObjectScript.Enable()
  if game.GetNewGamePlus() then
    return
  end
  chestOpen = true
  local riv200 = game.FindLevel("Riv200_DangersMain")
  if riv200 ~= nil then
    riv200:CallScript("EnableDebrisLift")
  end
  AwardTrophy()
  timer.StartLevelTimer(0.25, SetupSequence)
end
function AwardTrophy()
  print("Trophy Awarded: Nice Moves")
  game.UnlockTrophy(16)
end
function SetupSequence()
  local seq = LD.CreateCineSequence(thisLevel, GameObjects.EntZn_CheckSonOccupied, "Runic Attack Tutorial")
  seq:Do(function()
    if Player:GetCurrentWeapon() ~= "Axe" then
      uiCalls.SendSidebarDesignerMessage({
        Text = 18027,
        AdvanceType = uiCalls.msgParam.INFINITE_TIMER,
        Critical = true
      })
    end
  end)
  seq:WaitForFunctionTrue(function()
    return Player:GetCurrentWeapon() == "Axe"
  end)
  seq:Do(function()
    uiCalls.UI_Event_ClearAllDesignerMessages()
    LD.CallFunctionAfterDelay(function()
      TUT.Specials_Tutorial()
      specialsMessageOn = true
    end, 0.15)
  end)
  seq:Do(StartTutorialMsgTimer)
  seq:WaitForFunctionTrue(function()
    return Player:IsPlayingMove("MOV_AxeSpecialQuickClear")
  end)
  seq:Do(RunicAttackUsed)
  seq:StartSequence()
end
function StartTutorialMsgTimer()
  weaponSpecialTimer = timer.StartLevelTimer(4, CheckForWeaponSpecial)
end
function CheckForWeaponSpecial()
  if Player:GetCurrentWeapon() == "Axe" then
    if not specialsMessageOn then
      TUT.Specials_Tutorial()
      specialsMessageOn = true
    end
  elseif specialsMessageOn then
    uiCalls.SendSidebarDesignerMessage({
      Text = 18027,
      AdvanceType = uiCalls.msgParam.INFINITE_TIMER,
      Critical = true
    })
    specialsMessageOn = false
  end
  weaponSpecialTimer:Restart()
end
function RunicAttackUsed()
  weaponSpecialTimer:Stop()
  timer.StartLevelTimer(0.15, function()
    uiCalls.UI_Event_ClearAllDesignerMessages()
  end)
  timer.StartLevelTimer(0.15, function()
    GameObjects.ReactionStim.LuaObjectScript.Trigger()
  end)
  timer.StartLevelTimer(0.25, function()
    GameObjects.CA_RunicIdle.LuaObjectScript.Disable()
    GameObjects.CA_Area1_LiftGate.LuaObjectScript.Enable()
  end)
  timer.StartLevelTimer(0.3, function()
    game.AI.FindSon():CallScript("ClearBehaviorContext")
  end)
  timer.StartLevelTimer(0.35, RemoveSonOccupied)
end
function CA_EnableIntro()
  GameObjects.CA_SyncExit.LuaObjectScript.Enable()
  GameObjects.LTW_ToPillarLift.LuaObjectScript.Enable()
  son:CallScript("EnterBehaviorContext", "LEAD_THE_WAY_BEHAVIOR_CONTEXT_CONFIG")
  if game.Level.GetVariable("CompletedCineNumber") < 115 then
    GameObjects.CA_Area1_LiftGate.LuaObjectScript.Enable()
  end
end
function CA_DisableIntro()
  GameObjects.LTW_ToPillarLift.LuaObjectScript.Disable()
  son:CallScript("ClearBehaviorContext")
  GameObjects.CA_Area1_LiftGate.LuaObjectScript.Disable()
end
function OnEvaluateLoadGroup_LoadGroup_AI()
  if game.Level.GetVariable("CompletedCineNumber") < 115 then
    return "BridgeCollapse"
  else
    return nil
  end
end
function TutorialMessage()
end
function SetSonOccupied()
  if game.GetNewGamePlus() then
    return
  end
  local availabilityState = {Unoccupied = false}
  son:SetNewAvailabilityRequest("LevelDesignScript", availabilityState)
end
function RemoveSonOccupied()
  son:RemoveAvailabilityRequest("LevelDesignScript")
  chestOpen = false
  game.World.StoreCheckpoint({
    OverrideObject = GameObjects.CheckpointOverride
  })
end
function LTW_Update_ToPillar()
  local toPillarParams = {
    Speed = 4.75,
    LeaderDistance_Wait = 14,
    LeaderDistance_Continue = 8,
    LeaderDistance_Backtrack = 18,
    LeaderDistance_BacktrackDone = 12
  }
  GameObjects.LTW_ToPillarLift.Child.LuaObjectScript.UpdateLeadTheWayParams(toPillarParams)
end
function LoadCheck_Riv200()
  game.UI.LoadCheck("Riv200_DangersMain")
end
function OnSaveCheckpoint(level)
  return {
    levelstate = checkpoint.Save(),
    chestOpen = chestOpen,
    bookmarkSaved = bookmarkSaved
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  checkpoint.Restore(savedInfo.levelstate)
  chestOpen = savedInfo.chestOpen
  bookmarkSaved = savedInfo.bookmarkSaved
end
