local LD = require("design.LevelDesignLibrary")
local EC = require("design.Encounter")
local checkpoint = require("level.checkpoint")
local monitors = require("level.MonitorLibrary")
timer = require("level.timer")
local TUT = require("game.GlobalTutorials")
local CCOS = require("camera.camera_oneshot")
local uiCalls = require("ui.uicalls")
axe = nil
player = nil
local thisLevel, bellsComplete, runeCompleted, Area_1_Encounter_1, Area_1_Encounter_2, ZoneMonitor_1, ZoneMonitor_2, ZoneMonitor_3, A1_ZM_1, Stop_A1_EC_Monitor, Start_A1_EC_Monitor, Start_A1_EC_Repop, Enemy_HealthMonitor, oneShotRiverTroll
function OnScriptLoaded(level)
  player = game.Player.FindPlayer()
  thisLevel = level
  Area_1_Fight_1()
  Area_1_Fight_2()
  GameObjects.NavMeshHelper:Hide()
end
function OnFirstStart()
  GameObjects.BanterLookAt_Chest.LuaObjectScript.Disable()
end
function OnStart()
  GameObjects.LeashZone_Far:HideEntityVolume()
  GameObjects.LeashZone_Short:HideEntityVolume()
  SoundOnStart()
  if Area_1_Encounter_1:WasRunning() then
    Area_1_Encounter_1:Start()
  end
end
function OnUpdate(level)
  if oneShotRiverTroll ~= nil then
    oneShotRiverTroll:Update()
  end
end
function OnUseWorld(level)
end
function OnSaveCheckpoint(level, obj, savedInfo)
  return {
    levelstate = checkpoint.Save(),
    bellsComplete = bellsComplete
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  checkpoint.Restore(savedInfo.levelstate)
  bellsComplete = savedInfo.bellsComplete
end
function OnEvaluateLoadGroup_Cinematic()
  if game.Level.GetVariable("CompletedCineNumber") <= 136 then
    return "BoarIntroConfig"
  else
    return nil
  end
end
function LoadCheck_Riv430()
  game.UI.LoadCheck("Riv430_ForestBoarTrack")
end
function RuneReadComplete()
  runeCompleted = true
end
function EnableRuneReadArea()
  GameObjects.CA_WaitAboveRope.LuaObjectScript.Disable()
  if not runeCompleted then
    GameObjects.CA_AreaClimb_Forward_01.LuaObjectScript.Enable()
  end
end
function DisableRuneReadArea()
  GameObjects.CA_AreaClimb_Forward_01.LuaObjectScript.Disable()
end
function CA_Area1_Enable()
  game.AI.FindSon():CallScript("EnterBehaviorContext", "WAIT_AND_EXPLORE_BEHAVIOR_CONTEXT_CONFIG")
  GameObjects.EntZn_WaitAndExplore:ShowEntityVolume()
  GameObjects.CA_Area1_Ground_02.LuaObjectScript.Enable()
  GameObjects.CA_Area4_Up_01.LuaObjectScript.Enable()
  GameObjects.CA_Area2_Vista.LuaObjectScript.Enable()
  GameObjects.CA_Area3_Ground_02.LuaObjectScript.Enable()
end
function CA_Area1_Disable()
  GameObjects.CA_Area1_Ground_02.LuaObjectScript.Disable()
  GameObjects.CA_Area2_Chest.LuaObjectScript.Disable()
  GameObjects.CA_Area2_Vista.LuaObjectScript.Disable()
  GameObjects.CA_Area3_Ground_02.LuaObjectScript.Disable()
  GameObjects.CA_Area4_Up_01.LuaObjectScript.Disable()
  game.AI.FindSon():CallScript("ClearBehaviorContext")
end
function CA_SwitchTo_Start()
  game.AI.FindSon():CallScript("ClearBehaviorContext")
end
function DisableSplines()
  GameObjects.LTW_Main_Lead.LuaObjectScript.Disable()
  GameObjects.LTW_Side_Lead.LuaObjectScript.Disable()
end
function BellChestOpen()
  bellsComplete = true
  GameObjects.CA_Area2_Chest.LuaObjectScript:Disable()
end
function BellsStarted()
  if not bellsComplete then
    GameObjects.CA_Area2_Chest.LuaObjectScript.Enable()
  end
end
function Area_1_Fight_1()
  Area_1_Encounter_1 = EC.NewEncounter(thisLevel, "[Riv420]EC: Fire Troll", {
    CheckpointOnComplete = true,
    CheckpointOverrideObject = GameObjects.ChkOvr_Riv420Middle.Child,
    LeashZone = "LshZn_Riv420_TrollEnc"
  })
  Area_1_Encounter_1:AddWave({
    {
      spawners = "Troll_F_BURST",
      markerID = "Troll",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 2
    },
    {
      spawners = "Fanatic_Kneel2",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    },
    {
      spawners = "Fanatic_Alerted",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    }
  })
  Area_1_Encounter_1:AddWave({
    triggerWaveFromScript = true,
    {
      spawners = "Fanatic_N_SFG",
      spawnLocators = "A1_O_Loc_2",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 1.2
    }
  })
  Area_1_Encounter_1:AddWave({
    triggerWaveFromScript = true,
    {
      spawners = "Fanatic_N_SFG",
      spawnLocators = "A1_O_Loc_6",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 2.2
    },
    {
      spawners = "Fanatic_N_SFG",
      spawnLocators = "A1_O_Loc_7",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 6.2
    }
  })
  Area_1_Encounter_1:AddWave({
    requireCompletionOfAllPriorWaves = true,
    {
      spawners = "Fanatic_N_SFG",
      spawnLocators = "A1_O_Loc_2",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0.3
    },
    {
      spawners = "Fanatic_N_SFG",
      spawnLocators = "A1_O_Loc_7",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 2.2
    },
    {
      spawners = "Fanatic_T_SFG",
      spawnLocators = "A1_O_Loc_5",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 6.8
    }
  })
  Area_1_Encounter_1:OnEnemySpawn(Troll_Health_Monitor, {markerID = "Troll"})
  Area_1_Encounter_1:OnEnemyDeath(riv420TrollDead, {markerID = "Troll"})
  Area_1_Encounter_1:OnCombatStart(function()
    if Area_1_Encounter_1:WavesComplete(1) == false then
      LD.StartCombatMusic("SND_MX_RIV_troll_fight_in", "SND_fake_id")
    end
  end)
  Area_1_Encounter_1:OnComplete(EncounterComplete)
  Start_A1_EC_Monitor = monitors.CreateEntityZoneMonitor(player, GameObjects.EntZn_Area_1_Spawn)
  Start_A1_EC_Monitor:SetTriggerCountLimit(1)
  Start_A1_EC_Monitor:OnEnter(function()
    local cineNumber = game.Level.GetVariable("CompletedCineNumber")
    if Area_1_Encounter_1 ~= nil and cineNumber <= 136 and not Area_1_Encounter_1:IsRunning() and not Area_1_Encounter_1:IsComplete() then
      Area_1_Encounter_1:Start()
      GameObjects.LeashZone_Far:ShowEntityVolume()
      GameObjects.LeashZone_Short:ShowEntityVolume()
      timer.StartLevelTimer(2.6, CameraStartTrollIntro)
      timer.StartLevelTimer(4.9, function()
        GameObjects.EnvStim_TrollIntro.LuaObjectScript.Trigger()
      end)
    end
  end)
end
function Alert_Area_1_Fight_2()
  local cineNum = game.Level.GetVariable("CompletedCineNumber")
end
function Area_1_Fight_2()
  Area_1_Encounter_2 = EC.NewEncounter(thisLevel, "[Riv420]EC: Repopulation", {
    CheckpointOnComplete = true,
    CheckpointOverrideObject = GameObjects.ChkOvr_Riv420Middle.Child,
    LeashZone = "LshZn_Riv420_TrollEnc",
    AutoResetOnReload = true,
    RepopulationEncounter = true,
    MustHaveCompletedList = {
      "[Riv420]EC: Fire Troll"
    }
  })
  Area_1_Encounter_2:AddWave({
    {
      spawners = "Wolf_P_SECU",
      spawnLocators = "A1_D_Loc_1",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0.03
    },
    {
      spawners = "Seidr_SDBR",
      spawnLocators = "A1_D_Loc_2",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0.05
    },
    {
      spawners = "Wolf_P_SECU",
      spawnLocators = "A1_D_Loc_3",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 2
    },
    {
      spawners = "Seidr_SDBR",
      spawnLocators = "A1_D_Loc_4",
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0.03
    }
  })
  Area_1_Encounter_2:OnEnemyDeath(function()
    Area_1_Encounter_2:AlertEnemies()
  end, {count = 1})
  Start_A1_EC_Repop = monitors.CreateEntityZoneMonitor(player, GameObjects.Out_Of_Bounds_Zones)
  Start_A1_EC_Repop:OnEnter(function()
    local cineNum = game.Level.GetVariable("CompletedCineNumber")
    if 330 <= cineNum then
      Area_1_Encounter_2:Start()
    end
  end)
end
function IsLookingAtTrollSmashMoment()
  local orbitrotation = game.Camera.GetOrbitRotation()
  local moreThanThisValue, lessThanThisValue
  if 0 < orbitrotation then
    moreThanThisValue = 112
    lessThanThisValue = 180
  else
    moreThanThisValue = -180
    lessThanThisValue = -80
  end
  if orbitrotation <= lessThanThisValue and orbitrotation >= moreThanThisValue then
    return true
  end
  return false
end
function CameraStartTrollIntro()
  if IsLookingAtTrollSmashMoment() == false then
    return
  end
  player:SetMaxSpeedOverride(3)
  timer.StartLevelTimer(2.5, function()
    player:ClearMaxSpeedOverride()
  end)
  oneShotRiverTroll = CCOS.OneShotCamera.New("PLYR_Nar_Intro_RiverTroll", 2)
  oneShotRiverTroll:Start()
  oneShotRiverTroll:SetCallback(CameraDestroyTrollIntro)
end
function CameraDestroyTrollIntro()
  oneShotRiverTroll = nil
end
function EnableIntroContext()
  GameObjects.EntZn_IntroContext:ShowEntityVolume()
  game.AI.FindSon():CallScript("EnterBehaviorContext", "ALERT_BEHAVIOR_CONTEXT_CONFIG")
end
function EncounterComplete()
  GameObjects.EntZn_IntroContext:HideEntityVolume()
  LD.CallFunctionAfterDelay(function()
    GameObjects.BanterLookAt_Chest.LuaObjectScript.Enable()
  end, 6)
  GameObjects.CA_Intro.LuaObjectScript.Disable()
  GameObjects.LTW_Main_Lead.LuaObjectScript.Enable()
  GameObjects.LTW_Side_Lead.LuaObjectScript.Enable()
  timer.StartLevelTimer(6, function()
    TUT.SkillPointReminder_Tutorial()
  end)
  timer.StartLevelTimer(6, CA_Area1_Enable)
  GameObjects.LeashZone_Far:HideEntityVolume()
  GameObjects.LeashZone_Short:HideEntityVolume()
  GameObjects.Intro_OnAlert.LuaObjectScript.Disable()
  LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Seidr_Fanatic")
  LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Troll_Brenna_Daudi")
  game.Audio.PlayBanterNonCritical("EncEnd_2ndTroll")
end
function WoodBroken()
  GameObjects.Riv420SonBoost.LuaObjectScript.Enable()
end
function Trigger_Out_Of_Bounds()
  player:AddMarker("Out_Of_Bounds")
end
function Trigger_In_Bounds()
  player:RemoveMarker("Out_Of_Bounds")
end
function Trigger_LeashZone_Short()
  print("Trigger_LeashZone_Short")
end
function Trigger_LeashZone_Far()
  print("Trigger_LeashZone_Far")
end
function Troll_Health_Monitor(Enemy)
  if Enemy ~= nil then
    local EnemyHealth = Enemy:GetHitPoints()
    Enemy_HealthMonitor = monitors.CreateHealthMonitor(Enemy)
    local Health_Phase_1 = EnemyHealth * 0.89
    local Health_Phase_2 = EnemyHealth * 0.55
    local Health_Phase_3 = EnemyHealth * 0.258
    Enemy_HealthMonitor:OnHealthLessThan(Health_Phase_1, function()
      Area_1_Encounter_1:StartWave()
    end)
    Enemy_HealthMonitor:OnHealthLessThan(Health_Phase_2, function()
      Area_1_Encounter_1:StartWave()
    end)
    Enemy_HealthMonitor:OnHealthLessThan(Health_Phase_2, function()
      Area_1_Encounter_1:StartWave()
    end)
    game.Audio.SetWwiseSwitch(Enemy, "CHR_Variation", "CHR_Variation_02")
  end
end
function WakeSleeping(encounter)
  local waveXEnemies = encounter:GetActiveEnemies(1)
  local delay = math.random()
  for _, enemy in ipairs(waveXEnemies) do
    WakeMe(enemy)
  end
end
function WakeMe(enemy)
  if enemy ~= nil then
    enemy:TriggerMoveEvent("kLEAlert")
    enemy:CallScript("LuaHook_SetInCombatState")
  end
end
function SoundOnStart()
  GameObjects.Riv420_Loremarker:FindSingleGOByName("pSonReadRune").LuaObjectScript.LoreMarkerRuneReadSoundSetup()
end
local riv420TrollMusic = false
function riv420TrollDead()
  if riv420TrollMusic == false then
    game.Audio.StartMusic("SND_MX_RIV_troll_fight_out")
  end
end
function riv420TrollCSMusic()
  game.Audio.StartMusic("SND_MX_RIV_troll_fight_cs_kill")
  riv420TrollMusic = true
end
