local LD = require("design.LevelDesignLibrary")
local timers = require("level.timer")
local color = require("core.color")
local CSL = require("camera.shakelibrary")
local actor = require("narrative.actor")
local ND = require("design.NarrativeDesignLibrary")
local thisLevel, player, LW_R1_Door1, LW_R1_Door2, LW_R2_Door1, LW_Trap1_monitor, LW_Trap2_monitor, turretA, turretB, kraActor
local playerLeftRoom1 = false
local bCrawlsEnabled = false
local breakSequence
local bTurretAActive = false
local bTurretBActive = false
local encounterMusicOn = false
local encountersComplete = false
local bRuneReadStarted = false
function OnScriptLoaded(level)
  thisLevel = level
  LW_R1_Door1 = thisLevel:GetGameObject("LW_R1_Door1")
  LW_R1_Door2 = thisLevel:GetGameObject("LW_R1_Door2")
  LW_R2_Door1 = thisLevel:GetGameObject("LW_R2_Door1")
end
function OnPreStart(level)
  local INT_89667_Fixup = function()
    if game.Player.FindPlayer():InsideZone(GameObjects.Room2DetectionVolume) then
      return
    end
    if LD.GetEntityVariable("CAL_TempleFlip_LeftChainPulled") == true then
      return
    end
    local firstSawRetractDrain = GameObjects.drainSawBladeTrap1:FindSingleGOByName("drain").LuaObjectScript
    local firstSawRotateDrain = GameObjects.BifrostDrainCrystal6.LuaObjectScript
    local drainVaultDrainLeft = GameObjects.DrainVault:FindSingleGOByName("LeftDrain").LuaObjectScript
    local drainVaultDrainRight = GameObjects.DrainVault:FindSingleGOByName("RightDrain").LuaObjectScript
    local secondSawSetRightSawDrain = GameObjects.drainSawBladeTrap4:FindSingleGOByName("drain").LuaObjectScript
    local secondSawSetRightSaw = GameObjects.drainSawBladeTrap4.LuaObjectScript
    local FrontAreaHasAvailableCharge = function()
      return firstSawRetractDrain.GetActive() == true or firstSawRotateDrain.GetActive() == true or drainVaultDrainLeft.GetActive() == true or drainVaultDrainRight.GetActive() == true
    end
    if FrontAreaHasAvailableCharge() == false and secondSawSetRightSawDrain.GetActive() == true then
      drainVaultDrainLeft.OverrideStartActive(true)
      secondSawSetRightSawDrain.OverrideStartActive(false)
      secondSawSetRightSaw.OverrideRetractedState(false)
    end
  end
  INT_89667_Fixup()
end
function OnFirstStart(level)
  GameObjects.turret3:Hide()
  GameObjects.turret4:Hide()
  LW_R1_Door1:PlayAnimToEnd()
  LW_R1_Door2:PlayAnimToEnd()
  LW_R2_Door1:PlayAnimToEnd()
end
function OnStart(level, obj)
  if bCrawlsEnabled then
    EnableCrawls()
  else
    DisableCrawls()
  end
  SoundOnStart()
  if bTurretAActive then
    turretA.LuaObjectScript.Disable()
    timers.StartLevelTimer(4, function()
      turretA.LuaObjectScript.Enable()
    end)
  end
  if bTurretBActive then
    turretB.LuaObjectScript.Disable()
    timers.StartLevelTimer(4, function()
      turretB.LuaObjectScript.Enable()
    end)
  end
  if not bRuneReadStarted then
    GameObjects.rune_19.Child:JumpAnimToFrame(0)
    GameObjects.rune_19.Child:PauseAnim()
  else
    local animLength = GameObjects.rune_19.Child.AnimLengthFrames
    GameObjects.rune_19.Child:JumpAnimToFrame(animLength)
    GameObjects.rune_19.Child:PlayAnimToEnd()
    HideRuneEffects()
  end
end
function OnSaveCheckpoint(level)
  return {
    bCrawlsEnabled = bCrawlsEnabled,
    turretA = turretA,
    turretB = turretB,
    playerLeftRoom1 = playerLeftRoom1,
    bTurretAActive = bTurretAActive,
    bTurretBActive = bTurretBActive,
    encounterMusicOn = encounterMusicOn,
    encountersComplete = encountersComplete,
    bRuneReadStarted = bRuneReadStarted
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  bCrawlsEnabled = savedInfo.bCrawlsEnabled
  turretA = savedInfo.turretA
  turretB = savedInfo.turretB
  playerLeftRoom1 = savedInfo.playerLeftRoom1
  bTurretAActive = savedInfo.bTurretAActive
  bTurretBActive = savedInfo.bTurretBActive
  encounterMusicOn = savedInfo.encounterMusicOn
  encountersComplete = savedInfo.encountersComplete
  bRuneReadStarted = savedInfo.bRuneReadStarted
end
function EnableLeftDoor()
  GameObjects.LeftWingDoor.LuaObjectScript.Enable()
end
function OpenTraps()
  GameObjects.SawControl.LuaObjectScript.OpenAllTraps()
end
function StartLeftEncounter()
  timers.StartLevelTimer(4, function()
    if not LD.GetEntityVariable("CAL_TempleFlip_RightChainPulled") then
      game.Audio.PlayBanter("150_PostFirstChainB")
    end
    turretA.LuaObjectScript.Enable()
    GameObjects.PullUpSaw:PlayAnimToEnd()
  end)
  local cal740AI = game.FindLevel("Cal740_LeftWingAI")
  cal740AI:CallScript("StartEncounterL3")
end
function BreakChainLeft()
  GameObjects.SonGuardRail:Hide()
  DisableCrawls()
  GameObjects.SawControl.LuaObjectScript.RestartAllTraps()
  GameObjects.ObserveTemple.LuaObjectScript.Disable()
  if LD.GetEntityVariable("CAL_TempleFlip_RightChainPulled") then
    GameObjects.turret3:Show()
    GameObjects.turret1:Hide()
    turretA = GameObjects.turret3
  else
    GameObjects.turret1:Show()
    GameObjects.turret3:Hide()
    turretA = GameObjects.turret1
  end
  turretA.LuaObjectScript.Expose()
  bTurretAActive = true
  timers.StartLevelTimer(1, StartLeftEncounter)
  LW_R2_Door1:PlayAnimationToFrame(0, {Rate = 3.5})
  GameObjects.ChainCollision:HideCollision()
  CSL.PlayDefaultShake("FireTurretRiseAndStop", 1.3)
  game.Audio.StartCheckpointedMusic("SND_MX_CAL_temple_flip_fight_11_in")
end
function LW_Encounter3Done()
  timers.StartLevelTimer(2, function()
    LW_R2_Door1:PlayAnimToEnd()
    CheckPoint_3()
  end)
  turretA.LuaObjectScript.Disable()
  bTurretAActive = false
  turretA.LuaObjectScript.Lock()
end
function LW_Door_down()
  LW_R2_Door1:PlayAnimationToEnd()
  EnableCrawls()
  GameObjects.RunToEncounter4.LuaObjectScript.Enable()
  GameObjects.CombatCA1.LuaObjectScript.Enable()
  GameObjects.CombatCA2.LuaObjectScript.Enable()
  GameObjects.CombatCA3.LuaObjectScript.Enable()
  GameObjects.CombatCA4.LuaObjectScript.Enable()
end
function LW_Encounter4Started()
  GameObjects.RunToEncounter4.LuaObjectScript.Disable()
  if LD.GetEntityVariable("CAL_TempleFlip_RightChainPulled") then
    GameObjects.turret4:Show()
    GameObjects.turret2:Hide()
    turretB = GameObjects.turret4
  else
    GameObjects.turret2:Show()
    GameObjects.turret4:Hide()
    turretB = GameObjects.turret2
  end
  turretB.LuaObjectScript.Expose()
  bTurretBActive = true
  timers.StartLevelTimer(4, function()
    turretB.LuaObjectScript.Enable()
  end)
  encounterMusicOn = true
end
function LW_Encounter4Done()
  GameObjects.SonGuardRail:Show()
  timers.StartLevelTimer(2, function()
    LW_R1_Door2:PlayAnimToEnd()
    LW_R2_Door1:PlayAnimToEnd()
    LW_R1_Door1:PlayAnimToEnd()
    CheckPoint_4()
  end)
  turretB.LuaObjectScript.Disable()
  bTurretBActive = false
  turretB.LuaObjectScript.Lock()
  LeftWingMusicDone()
end
function CheckPoint_3()
  game.World.StoreCheckpoint({
    OverrideObject = GameObjects.LW_CheckpointOverride3.Child
  })
end
function CheckPoint_4()
  game.World.StoreCheckpoint({
    OverrideObject = GameObjects.LW_CheckpointOverride4.Child
  })
end
function EnableCrawls()
  bCrawlsEnabled = true
  GameObjects.CubbyHoleManager1.LuaObjectScript.Enable()
  GameObjects.CubbyHoleManager2.LuaObjectScript.Enable()
  GameObjects.CubbyHoleManager1.LuaObjectScript.ClearActiveHole()
  GameObjects.CubbyHoleManager2.LuaObjectScript.ClearActiveHole()
end
function DisableCrawls()
  bCrawlsEnabled = false
  GameObjects.CubbyHoleManager1.LuaObjectScript.Disable()
  GameObjects.CubbyHoleManager2.LuaObjectScript.Disable()
end
function EnableRoomAfterBanter()
  GameObjects.SonReadRune.LuaObjectScript.Enable()
end
function Crawl1Exit()
  if not playerLeftRoom1 then
    GameObjects.ObserveSaw.LuaObjectScript.Enable()
  end
end
function Crawl2Enter()
  GameObjects.ObserveSaw.LuaObjectScript.Disable()
  playerLeftRoom1 = true
end
function Crawl2Exit()
  GameObjects.ObserveTemple.LuaObjectScript.Enable()
end
function Forward_DeathTrapsCrawl()
  game.UI.LoadCheck("Cal720_LowerCenterRoom")
  game.FindLevel("Cal720_LowerCenterRoom"):GetGameObject("Cal720_Banter"):CallScript("DeathTraps_Crawl")
end
function DisableAllCA()
  DisableCrawls()
  GameObjects.ObserveSaw.LuaObjectScript.Disable()
  GameObjects.ObserveTemple.LuaObjectScript.Disable()
  GameObjects.RunToEncounter4.LuaObjectScript.Disable()
  if LD.GetEntityVariable("CAL_TempleFlip_RightChainPulled") then
    GameObjects.CombatCA1.LuaObjectScript.Disable()
    GameObjects.CombatCA2.LuaObjectScript.Disable()
    GameObjects.CombatCA3.LuaObjectScript.Disable()
    GameObjects.CombatCA4.LuaObjectScript.Disable()
  end
end
function DisableRevive()
  game.Player.FindPlayer():CallScript("LuaHook_DisableRevive", true)
end
function EnableRevive()
  game.Player.FindPlayer():CallScript("LuaHook_DisableRevive", false)
end
function MakeNervous()
  game.AI.FindSon():CallScript("EnterBehaviorContext", "NERVOUS_BEHAVIOR_CONTEXT_CONFIG")
end
function ClearNervous()
  game.AI.FindSon():CallScript("ClearBehaviorContext")
end
function StartRuneRead()
  if not bRuneReadStarted then
    local wallEmitter = GameObjects.RuneReading:FindSingleSoundEmitterByName("SNDSonKnowledge")
    GameObjects.rune_19.Child:PlayAnimToEnd()
    LD.PlaySound(wallEmitter, "SND_MAG_Rune_Read_Burn_Away_LP")
    GameObjects.rune_19.Child:OnAnimDone(thisLevel, "HideRuneEffects")
    LD.UpdateJournal("CAL_740_Lore_01", 1)
    LD.ActivateAndIncrementQuest("RegionSummary_CALT_LoreMarker_Parent")
    game.Audio.PlayBanter("Cal740_RuneGraffiti")
    bRuneReadStarted = true
  end
end
function HideRuneEffects()
  if GameObjects.rune_19.Child then
    local wallEmitter = GameObjects.RuneReading:FindSingleSoundEmitterByName("SND_WellRead")
    LD.StopSound(wallEmitter, "SND_MAG_Rune_Read_Burn_Away_LP")
    LD.HideFX(GameObjects.RuneReading.Child)
  end
end
function InterruptCrawl1()
  local son = game.AI.FindSon()
  local hole1 = GameObjects.CubbyHoleManager1:FindSingleGOByName("Hole_1").Child
  local hole2 = GameObjects.CubbyHoleManager1:FindSingleGOByName("Hole_2").Child
  if son.OwnedPOI and (son:IsPlayingMove("MOV_CA_Crawl_Enter") or son.OwnedPOI:GetStageName() == "Approach") and (son.OwnedPOI == hole1 or son.OwnedPOI == hole2) then
    GameObjects.CubbyHoleManager1.LuaObjectScript.InstantExit()
  end
end
function InterruptCrawl2()
  local son = game.AI.FindSon()
  local hole1 = GameObjects.CubbyHoleManager2:FindSingleGOByName("Hole_1").Child
  local hole2 = GameObjects.CubbyHoleManager2:FindSingleGOByName("Hole_2").Child
  if son.OwnedPOI and (son:IsPlayingMove("MOV_CA_Crawl_Enter") or son.OwnedPOI:GetStageName() == "Approach") and (son.OwnedPOI == hole1 or son.OwnedPOI == hole2) then
    GameObjects.CubbyHoleManager2.LuaObjectScript.InstantExit()
  end
end
function SoundOnStart()
  SoundOverrides()
end
function SoundOverrides()
  local emitters = GameObjects.SNDGrpCal740Trap.SoundEmitters
  GameObjects.SawControl.LuaObjectScript.OverrideTrapSounds(emitters)
end
function LeftHallBladeMusic()
end
function LW_MusicOn()
  if LD.GetEntityVariable("CAL_TempleFlip_LeftChainPulled") and not encountersComplete and not encounterMusicOn then
    game.Audio.StartCheckpointedMusic("SND_MX_CAL_temple_flip_fight_11_in")
    encounterMusicOn = true
  end
end
function LW_MusicOff()
  if encounterMusicOn then
    game.Audio.StartMusic("SND_MX_CAL_temple_flip_fight_11_out")
    encounterMusicOn = false
  end
end
function LeftWingMusicDone()
  game.Audio.StartMusic("SND_MX_CAL_temple_flip_fight_11_out")
  encounterMusicOn = false
  encountersComplete = true
end
function AbortTryptich()
  game.FindLevel("Cal720_LowerCenterRoom"):CallScript("DisableTryptich")
end
function FinalCheck()
  local son = game.AI.FindSon()
  local hole1 = GameObjects.CubbyHoleManager2:FindSingleGOByName("Hole_1").Child
  local hole2 = GameObjects.CubbyHoleManager2:FindSingleGOByName("Hole_2").Child
  if son.OwnedPOI then
    if son.OwnedPOI == hole1 or son.OwnedPOI == hole2 then
      if son:IsPlayingMove("MOV_CA_Crawl_Idle") then
        GameObjects.CubbyHoleManager2.LuaObjectScript.Emerge()
      elseif son.OwnedPOI:GetStageName() == "Approach" then
        InterruptCrawl2()
      end
    end
  elseif son:IsInsideEntityZone("FinalCheckLeft") then
    son:Warp(GameObjects.crawl1_InstantExit_pos:GetWorldPosition(), GameObjects.crawl1_InstantExit_pos:GetWorldForward())
  end
end
