timer = require("level.timer")
LD = require("design.LevelDesignLibrary")
EC = require("design.Encounter")
monitors = require("level.MonitorLibrary")
checkpoint = require("level.checkpoint")
local TUT = require("game.GlobalTutorials")
local player, thisLevel, Area_1_Encounter_1, Area_2_Encounter_1, Area_1_Encounter_2, Area_2_Encounter_2, DraugrKill_ZoneMonitor
ZM_A1_E1_Attack = nil
ZM_A2_E1_Attack = nil
function OnScriptLoaded(level)
  player = game.Player.FindPlayer()
  thisLevel = level
  Climb_Area_1_Fight_1()
  DraugrEnchant_Intro_Fight_1()
  Return_Crawler_Fight_1()
  Return_Shield_Patrol_Fight_1()
  SoundInit()
  ToggleCompassGateway()
end
function OnFirstStart(level)
  GameObjects.EntZn_Area_2_Return_Alert:HideEntityVolume()
  GameObjects.TraversePath_CaveCrawlSecret:HideTraversePath()
end
function OnStart(level)
  SoundOnStart()
  if Area_2_Encounter_2:WasRunning() then
    Area_2_Encounter_2:Start()
  end
  if game.Level.GetVariable("CompletedCineNumber") > 449 and Area_2_Encounter_2:IsComplete() == false then
    GameObjects.EntZn_Area_2_Return_Alert:ShowEntityVolume()
  elseif Area_2_Encounter_2:IsComplete() == true then
    GameObjects.EntZn_Area_2_Return_Alert:HideEntityVolume()
  end
end
function LoadCheckPeak190()
  game.UI.LoadCheck("Peak190_ChimneyEnter")
end
function LoadCheckPeak100()
  game.UI.LoadCheck("Peak100_Entrance")
end
function EnableCaveCrawlSecret()
  GameObjects.TraversePath_CaveCrawlSecret:ShowTraversePath()
end
function SCA_CrackClimbExit_Enable()
  GameObjects.SCA_CrackClimbExit.LuaObjectScript.Enable()
end
function ActivateRopeDropReturn()
  GameObjects.Son_RopeDropReturn:PlayAnimToEnd()
  GameObjects.Son_RopeDropReturn:ShowTraversePath()
end
function SCA_RopeDown_Down_Enable()
  GameObjects.SCA_RopeDown_Down.LuaObjectScript.Enable()
end
function SCA_RopeDown_Up_Enable()
  GameObjects.SCA_RopeDown_Up.LuaObjectScript.Enable()
end
function SonSyncOff()
  local availabilityState = {AvailableForSync = false}
  game.AI.FindSon():SetNewAvailabilityRequest("LevelDesignScript", availabilityState)
end
function SonSyncOn()
  game.AI.FindSon():RemoveAvailabilityRequest("LevelDesignScript")
end
function RuneReadActivate()
  GameObjects.RuneReadWall.Child:PlayAnimToEnd()
  PlaySoundCrackClimbRuneRead()
  timer.StartLevelTimer(4, function()
    LD.UpdateJournal("PP_180_Lore_01", 1)
    LD.ActivateAndIncrementQuest("RegionSummary_PP_LoreMarker_Parent")
  end)
end
function VibrateWallDestroyed()
  GameObjects.Btr_SapBackside.LuaObjectScript.SapBackside_Hide()
  GameObjects.Btr_SapBackside.LuaObjectScript.SapDiscovered_Hide()
  local peak100 = game.FindLevel("peak100_Entrance")
  if peak100 ~= nil then
    peak100:CallScript("SCA_VibrateDoorTrip1_Disable")
    peak100:CallScript("SCA_VibrateDoorTrip2_Disable")
  end
  GameObjects.InkTotem:FindSingleGOByName("SonInkObserve").LuaObjectScript.Enable()
end
function Set_Context_OnAlert()
  game.AI.FindSon():CallScript("EnterBehaviorContext", "ALERT_BEHAVIOR_CONTEXT_CONFIG")
end
function Area_1_Encounter_1_End()
  if Area_1_Encounter_1:IsComplete() and Area_2_Encounter_1:IsComplete() then
    local peak100 = game.FindLevel("Peak100_Entrance")
    if peak100 ~= nil then
      peak100:CallScript("SCA_SpreadDoor180_Combat_Disable")
    end
    GameObjects.Btr_LookingForCrack.LuaObjectScript.PlayLookingForCrack01()
    GameObjects.Btr_SapBackside.LuaObjectScript.SapBackside_Show()
    LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Draugr_Weapon")
    LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Draugr_Shield")
    game.World.StoreCheckpoint()
  end
end
function ToggleCompassGateway()
  if game.Wallets.HasResource("HERO", "ArrowUnlock_Shock") then
    game.Compass.SetGatewayMarkerIsOpen("PP_180_Helper", true)
  else
    game.Compass.SetGatewayMarkerIsOpen("PP_180_Helper", false)
  end
end
function StartEnchantIntro()
  if game.Level.GetVariable("CompletedCineNumber") <= 295 then
    Area_2_Encounter_1:Start()
  end
end
function Climb_Area_1_Fight_1()
  GameObjects.Btr_SapBackside.LuaObjectScript.SapBackside_Hide()
  Area_1_Encounter_1 = EC.NewEncounter(thisLevel, "[Area 3]EC: 2 Shield Draugr & Jump Down Shield", {CheckpointOnComplete = false})
  Area_1_Encounter_1:AddWave({
    {
      spawners = "Draugr_ENCH_SUSL_N_1",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    }
  })
  Area_1_Encounter_1:AddWave({
    {
      spawners = "Draugr_ENCHANT_2",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    },
    {
      triggerWaveFromScript = true,
      spawners = "Draugr_SH_SUSL_N_3",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    }
  })
  Area_1_Encounter_1:SetStartZone(thisLevel:GetGameObject("EntZn_Area_1_EC_1_Spawn"), {
    cineRequirement = {0, 295}
  })
  Area_1_Encounter_1:OnComplete(Area_1_Encounter_1_End)
  ZM_A1_E1_Attack = monitors.CreateEntityZoneMonitor(player, thisLevel:GetGameObject("EntZn_Area_1_EC_1_Attack"))
  ZM_A1_E1_Attack:OnEnter(function()
    Area_1_Encounter_1:StartWave(2)
    timer.StartLevelTimer(2, function()
      Area_1_Encounter_1:AlertEnemies()
    end)
  end)
end
function DraugrEnchant_Intro_Fight_1()
  Area_2_Encounter_1 = EC.NewEncounter(thisLevel, "[Area 3]EC: Power Arm Intro", {CheckpointOnComplete = false})
  Area_2_Encounter_1:AddWave({
    {
      spawners = "Draugr_ENCHANT_1",
      maxActive = 1,
      markerID = "IntroBehavior",
      totalSpawns = 1,
      spawnCooldown = 0.8
    }
  })
  Area_2_Encounter_1:OnComplete(Area_1_Encounter_1_End)
end
function WakeSleeping(encounter)
  local waveXEnemies = encounter:GetActiveEnemies(1)
  local delay = math.random()
  for key, enemy in ipairs(waveXEnemies) do
    timer.StartLevelTimer(math.random(key * 0.1 + 1), function()
      WakeMe(enemy)
    end)
  end
end
function WakeMe(enemy)
  enemy:TriggerMoveEvent("kLEAlert")
end
function Return_Crawler_Fight_1()
  Area_1_Encounter_2 = EC.NewEncounter(thisLevel, "[Area 3]EC: Return Fight Crawlers", {
    CheckpointOnComplete = false,
    LeashZone = "LeashZone180_2"
  })
  Area_1_Encounter_2:AddWave({
    {
      spawners = "Crawler10_S_1",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    },
    {
      spawners = "Crawler10_S_2",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 1
    },
    {
      spawners = "Crawler10_S_3",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 1
    }
  })
  Area_1_Encounter_2:SetStartZone(thisLevel:GetGameObject("EntZn_Area_1_Return_Spawn1"), {
    cineRequirement = {450, 500}
  })
  Area_1_Encounter_2:OnComplete(function()
    timer.StartLevelTimer(2.5, function()
      GameObjects.Btr_AFewWords:ShowEntityVolume()
      LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Tatzelwurm_Spitter")
    end)
  end)
  Area_1_Encounter_2:OnComplete(function()
    timer.StartLevelTimer(3, function()
      game.World.StoreCheckpoint()
    end)
  end)
end
function Return_Shield_Patrol_Fight_1()
  Area_2_Encounter_2 = EC.NewEncounter(thisLevel, "[Area 3]EC: Return Shield Patrol Fight", {
    CheckpointOnComplete = true,
    LeashZone = "LeashZone180_1"
  })
  Area_2_Encounter_2:AddWave({
    {
      spawners = "Draugr_SH_Patrol_01",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    },
    {
      spawners = "Draugr_SH_Idle",
      markerID = "KillTarget",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    }
  })
  Area_2_Encounter_2:SetStartZone(thisLevel:GetGameObject("EntZn_Area_2_Return_Spawn2"), {
    cineRequirement = {450, 500}
  })
  DraugrKill_ZoneMonitor = monitors.CreateEntityZoneMonitor(player, thisLevel:GetGameObject("EntZn_Area_2_Return_Alert"))
  DraugrKill_ZoneMonitor:OnEnter(function()
    game.Combat.TurnOnAndLockCombatStatus()
    local son = game.AI.FindSon()
    son:CallScript("LuaHook_SetToEnraged")
    timer.StartLevelTimer(1, function()
      game.AI.FindSon():TriggerMoveEvent("kLE_KillDraugr")
    end)
    Set_Context_OnAlert()
    timer.StartLevelTimer(0.5, function()
      game.Audio.PlayBanterNonCritical("SonJerk_Attack")
    end)
    timer.StartLevelTimer(1.5, function()
      Area_2_Encounter_2:AlertEnemies()
    end)
  end)
  DraugrKill_ZoneMonitor:SetTriggerCountLimit(1)
  Area_2_Encounter_2:OnComplete(function()
    LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Draugr_Shield")
    GameObjects.EntZn_Area_2_Return_Alert:HideEntityVolume()
  end)
end
function OnSaveCheckpoint(level)
  return {
    levelstate = checkpoint.Save()
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  checkpoint.Restore(savedInfo.levelstate)
end
function CameraResetRecentersLongClimbFWD()
  WakeUpTheRecenterZones("RecenterGroup_LongClimb")
end
function WakeUpTheRecenterZones(mayagroupname)
  print("Camera: Wake Up Recenter Group")
  local recentergroup = thisLevel:FindGameObject(mayagroupname)
  for _, child in pairs(recentergroup.Children) do
    child.Child.LuaObjectScript.Reset()
    game.SubObject.Wake(child.Child)
  end
end
function AnimateTrilobytes()
  GameObjects.TrilobyteGroup_01:PlayAnimToEnd()
  PlaySoundTrilobyteScurry()
  GameObjects.TrilobyteEntZoneGroup:Hide()
end
local soundTrilobyteEmitters = {}
local crackClimbRuneReadEmitter
function SoundInit()
  soundTrilobyteEmitters = GameObjects.TrilobyteGroup_01.SoundEmitters
  crackClimbRuneReadEmitter = GameObjects.RuneReadEmitter.SoundEmitters[1]
end
function PlaySoundTrilobyteScurry()
  for _, v in ipairs(soundTrilobyteEmitters) do
    LD.PlaySound(v, "SND_AMB_EMIT_Bats_Squeak_OneOff")
  end
end
function SoundOnStart()
  GameObjects.InkTotem:FindSingleGOByName("pSonReadRune").LuaObjectScript.LoreMarkerRuneReadSoundSetup()
end
function PlaySoundCrackClimbRuneRead()
  LD.PlayLoopingSoundToAnimFrame(crackClimbRuneReadEmitter, GameObjects.RuneReadWall.Child, "SND_MAG_Rune_Read_Burn_Away_LP", 35, 178)
end
function Peak180_FirstTripComplete()
  Area_1_Encounter_1:SetComplete()
end
function Peak180_FirstTripReturnComplete()
  LD.RemoveBreakable(GameObjects.vibrateSlab)
  GameObjects.BifrostVibrate_Fractured:Hide()
  GameObjects.BifrostVibrate_Fractured:HideCollision()
  GameObjects.Son_RopeDropReturn.LuaObjectScript.ActivateRopeDrop()
  GameObjects.Son_RopeDropReturn.Child.LuaObjectScript.Disable()
end
