local LD = require("design.LevelDesignLibrary")
local timers = require("level.timer")
local CSL = require("camera.shakelibrary")
local actor = require("narrative.actor")
local ND = require("design.NarrativeDesignLibrary")
local thisLevel, player, RW_R1_Door1, RW_R1_Door2, RW_R2_Door1
local bFloorBroken = false
local stomper4waiting = false
local turretA, turretB, kraActor
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
  RW_R1_Door1 = thisLevel:GetGameObject("RW_R1_Door1")
  RW_R1_Door2 = thisLevel:GetGameObject("RW_R1_Door2")
  RW_R2_Door1 = thisLevel:GetGameObject("RW_R2_Door1")
end
function OnFirstStart(level)
  GameObjects.turret3:Hide()
  GameObjects.turret4:Hide()
  RW_R1_Door1:PlayAnimToEnd()
  RW_R1_Door2:PlayAnimToEnd()
  RW_R2_Door1:PlayAnimToEnd()
  TurnOffHangingFires()
  GameObjects.stomperDown:HideCollision()
end
function OnStart(level, obj)
  local FirstHallwayInitialization = function()
    GameObjects.CrusherBlockTrap1.LuaObjectScript.ForceOpenCrusher(true)
    GameObjects.CrusherBlockTrap2.LuaObjectScript.ForceOpenCrusher(true)
    GameObjects.CrusherBlockTrap3.LuaObjectScript.ForceCloseCrusher(true)
    timers.StartLevelTimer(0.25, function()
      GameObjects.CrusherBlockTrap1.LuaObjectScript.Enable(true)
      GameObjects.CrusherBlockTrap2.LuaObjectScript.Enable(true)
    end)
    timers.StartLevelTimer(0.5, function()
      GameObjects.CrusherBlockTrap3.LuaObjectScript.Enable(true)
    end)
  end
  local SecondHallwayInitialization = function()
    GameObjects.CrusherBlockTrap4.LuaObjectScript.ForceCloseCrusher(true)
    GameObjects.CrusherBlockTrap5.LuaObjectScript.ForceOpenCrusher(true)
    GameObjects.CrusherBlockTrap6.LuaObjectScript.ForceCloseCrusher(true)
    if GameObjects.grate_Breakable.Child:GetBreakable().Broken == false then
      timers.StartLevelTimer(0.25, function()
        GameObjects.CrusherBlockTrap4.LuaObjectScript.Enable(true)
      end)
    else
      GameObjects.ObserveSap.LuaObjectScript.Disable()
      GameObjects.CrusherBlockTrap4.LuaObjectScript.ChangeCrusherDistance("6m")
      timers.StartLevelTimer(0.25, function()
        GameObjects.CrusherBlockTrap4.LuaObjectScript.Enable(true)
      end)
    end
    timers.StartLevelTimer(0.5, function()
      GameObjects.CrusherBlockTrap5.LuaObjectScript.Enable(true)
    end)
    timers.StartLevelTimer(0.75, function()
      GameObjects.CrusherBlockTrap6.LuaObjectScript.Enable(true)
    end)
  end
  if bCrawlsEnabled then
    EnableCrawls()
  else
    DisableCrawls()
  end
  GameObjects.navgeo:Hide()
  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 LD.GetEntityVariable("CAL_TempleFlip_RightChainPulled") then
    OpenAllTraps()
    timers.StartLevelTimer(1, RestartAllTraps)
  else
    FirstHallwayInitialization()
    SecondHallwayInitialization()
  end
  if not bRuneReadStarted then
    GameObjects.rune_18.Child:JumpAnimToFrame(0)
    GameObjects.rune_18.Child:PauseAnim()
  else
    local animLength = GameObjects.rune_18.Child.AnimLengthFrames
    GameObjects.rune_18.Child:JumpAnimToFrame(animLength)
    GameObjects.rune_18.Child:PlayAnimToEnd()
    HideRuneEffects()
  end
end
function OnSaveCheckpoint(level)
  return {
    bCrawlsEnabled = bCrawlsEnabled,
    turretA = turretA,
    turretB = turretB,
    bTurretAActive = bTurretAActive,
    bTurretBActive = bTurretBActive,
    bFloorBroken = bFloorBroken,
    encounterMusicOn = encounterMusicOn,
    encountersComplete = encountersComplete,
    bRuneReadStarted = bRuneReadStarted
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  bCrawlsEnabled = savedInfo.bCrawlsEnabled
  turretA = savedInfo.turretA
  turretB = savedInfo.turretB
  bTurretAActive = savedInfo.bTurretAActive
  bTurretBActive = savedInfo.bTurretBActive
  bFloorBroken = savedInfo.bFloorBroken
  encounterMusicOn = savedInfo.encounterMusicOn
  encountersComplete = savedInfo.encountersComplete
  bRuneReadStarted = savedInfo.bRuneReadStarted
end
function EnableRightDoor()
  GameObjects.RightWingDoor.LuaObjectScript.Enable()
end
function StartRightEncounter()
  if not LD.GetEntityVariable("CAL_TempleFlip_LeftChainPulled") then
    game.Audio.PlayBanter("150_PostFirstChainB")
  end
  timers.StartLevelTimer(4, function()
    turretA.LuaObjectScript.Enable()
  end)
  local cal750AI = game.FindLevel("Cal750_RightWingAI")
  cal750AI:CallScript("StartEncounterR3")
end
function ShatterFloorB()
  if not bFloorBroken then
    bFloorBroken = true
    GameObjects.ObserveSap.LuaObjectScript.Disable()
    GameObjects.CrusherBlockTrap4.LuaObjectScript.ChangeCrusherDistance("6m")
  end
end
function Trap4Down()
  if bFloorBroken then
    bFloorBroken = false
    stomper4waiting = true
    GameObjects.CrusherBlockTrap4.LuaObjectScript.Disable(false)
  end
end
function Trap5Down()
  if stomper4waiting then
    stomper4waiting = false
    GameObjects.CrusherBlockTrap4.LuaObjectScript.ForceOverrideState("Opening")
    GameObjects.CrusherBlockTrap4.LuaObjectScript.Enable(true)
  end
end
function OpenAllTraps()
  GameObjects.ObserveSap.LuaObjectScript.Disable()
  if not bFloorBroken then
    GameObjects.CrusherBlockTrap4.LuaObjectScript.ChangeCrusherDistance("6m")
    GameObjects.grate_Breakable:Hide()
    bFloorBroken = true
  end
  GameObjects.CrusherBlockTrap4.Child:HideCollision()
  GameObjects.stomperDown:ShowCollision()
  GameObjects.CrusherBlockTrap1.LuaObjectScript.ForceOpenCrusher(true)
  GameObjects.CrusherBlockTrap2.LuaObjectScript.ForceOpenCrusher(true)
  GameObjects.CrusherBlockTrap3.LuaObjectScript.ForceOpenCrusher(true)
  GameObjects.CrusherBlockTrap4.LuaObjectScript.ForceCloseCrusher(true)
  GameObjects.CrusherBlockTrap5.LuaObjectScript.ForceOpenCrusher(true)
  GameObjects.CrusherBlockTrap6.LuaObjectScript.ForceOpenCrusher(true)
end
function RestartAllTraps()
  GameObjects.CrusherBlockTrap1.LuaObjectScript.Enable(true)
  GameObjects.CrusherBlockTrap2.LuaObjectScript.Enable(true)
  GameObjects.CrusherBlockTrap3.LuaObjectScript.Enable(true)
  GameObjects.CrusherBlockTrap5.LuaObjectScript.Enable(true)
  GameObjects.CrusherBlockTrap6.LuaObjectScript.Enable(true)
end
function BreakChainRight()
  DisableCrawls()
  RestartAllTraps()
  GameObjects.ObserveTemple.LuaObjectScript.Disable()
  GameObjects.SonGuardRail:Hide()
  if LD.GetEntityVariable("CAL_TempleFlip_LeftChainPulled") then
    GameObjects.turret3:Show()
    GameObjects.turret1:Hide()
    turretA = GameObjects.turret3
  else
    GameObjects.turret1:Show()
    GameObjects.turret3:Hide()
    turretA = GameObjects.turret1
  end
  RW2_Door_up()
  turretA.LuaObjectScript.Expose()
  StartRightEncounter()
  bTurretAActive = true
  GameObjects.ChainCollision:HideCollision()
  CSL.PlayDefaultShake("FireTurretRiseAndStop", 1.3)
  game.Audio.StartCheckpointedMusic("SND_MX_CAL_temple_flip_fight_21_in")
  encounterMusicOn = true
end
function RW_Submerge_turretA()
end
function RW_Encounter3Done()
  timers.StartLevelTimer(2, function()
    CheckPoint_3()
  end)
  LD.StopCombatMusic()
  turretA.LuaObjectScript.Disable()
  bTurretAActive = false
  turretA.LuaObjectScript.Lock()
end
function RW_Encounter4Started()
  GameObjects.RunToEncounter4.LuaObjectScript.Disable()
  if LD.GetEntityVariable("CAL_TempleFlip_LeftChainPulled") 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()
    TurnOnHangingFires()
  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 TurnOffHangingFires()
  local fires = thisLevel:FindGameObjects("fireGroup_0*")
  local i = 0
  for _, fire in ipairs(fires) do
    i = i + 1
    timers.StartLevelTimer(i * 0.5, function()
      fire:Hide()
    end)
  end
end
function TurnOnHangingFires()
  local fires = thisLevel:FindGameObjects("fireGroup_0*")
  local i = 0
  for _, fire in ipairs(fires) do
    i = i + 1
    timers.StartLevelTimer(i * 0.5, function()
      fire:Show()
      if fire.Anim then
        fire:PlayAnimtionCycle()
      end
    end)
  end
end
function RW1_Door_up()
  RW_R1_Door2:PlayAnimationToEnd()
  RW_R1_Door1:PlayAnimationToEnd()
end
function RW1_Door_down()
  RW_R1_Door2:PlayAnimationToFrame(0, {Rate = -3.5})
end
function RW2_Door_up()
  RW_R2_Door1:PlayAnimationToFrame(0, {Rate = -3.5})
end
function RW2_Door_down()
  RW_R2_Door1:PlayAnimToEnd()
  EnableCrawls()
  GameObjects.RunToEncounter4.LuaObjectScript.Enable()
  GameObjects.CombatCA1.LuaObjectScript.Enable()
  GameObjects.CombatCA2.LuaObjectScript.Enable()
  GameObjects.CombatCA3.LuaObjectScript.Enable()
  GameObjects.CombatCA4.LuaObjectScript.Enable()
  GameObjects.CombatCA5.LuaObjectScript.Enable()
  GameObjects.CombatCA6.LuaObjectScript.Enable()
  GameObjects.CombatCA7.LuaObjectScript.Enable()
end
function RW_Encounter4Done()
  GameObjects.SonGuardRail:Show()
  timers.StartLevelTimer(2, function()
    RW_R1_Door2:PlayAnimToEnd()
    RW_R1_Door1:PlayAnimToEnd()
    RW_R2_Door1:PlayAnimToEnd()
    CheckPoint_4()
  end)
  turretB.LuaObjectScript.Disable()
  bTurretBActive = false
  turretB.LuaObjectScript.Lock()
  RightWingMusicDone()
end
function CheckPoint_3()
  game.World.StoreCheckpoint({
    OverrideObject = GameObjects.RW_CheckpointOverride3.Child
  })
end
function CheckPoint_4()
  game.World.StoreCheckpoint({
    OverrideObject = GameObjects.RW_CheckpointOverride4.Child
  })
end
function EnableRoomAfterBanter()
  GameObjects.SonReadRune.LuaObjectScript.Enable()
end
function KillPlayer()
  game.Combat.KillPlayer()
end
function SoundOnStart()
end
function RightHallAfterCrusherMusic()
end
function RW_MusicOn()
  if LD.GetEntityVariable("CAL_TempleFlip_RightChainPulled") and not encountersComplete and not encounterMusicOn then
    game.Audio.StartCheckpointedMusic("SND_MX_CAL_temple_flip_fight_21_in")
    encounterMusicOn = true
  end
end
function RW_MusicOff()
  if encounterMusicOn then
    game.Audio.StartMusic("SND_MX_CAL_temple_flip_fight_21_out")
    encounterMusicOn = false
  end
end
function RightWingMusicDone()
  game.Audio.StartMusic("SND_MX_CAL_temple_flip_fight_21_out")
  encounterMusicOn = false
  encountersComplete = true
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 DisableRevive()
  game.Player.FindPlayer():CallScript("LuaHook_DisableRevive", true)
end
function EnableRevive()
  game.Player.FindPlayer():CallScript("LuaHook_DisableRevive", false)
end
function Crawl1Exit()
  GameObjects.ObserveSap.LuaObjectScript.Enable()
end
function Crawl2Exit()
  GameObjects.ObserveTemple.LuaObjectScript.Enable()
end
function StartRuneRead()
  if not bRuneReadStarted then
    local wallEmitter = GameObjects.RuneReading:FindSingleSoundEmitterByName("SNDSonKnowledge")
    GameObjects.rune_18.Child:PlayAnimToEnd()
    LD.PlaySound(wallEmitter, "SND_MAG_Rune_Read_Burn_Away_LP")
    GameObjects.rune_18.Child:OnAnimDone(thisLevel, "HideRuneEffects")
    LD.UpdateJournal("CAL_750_Lore_01", 1)
    LD.ActivateAndIncrementQuest("RegionSummary_CALT_LoreMarker_Parent")
    game.Audio.PlayBanter("Cal750_RuneGraffiti")
    bRuneReadStarted = true
  end
end
function HideRuneEffects()
  if GameObjects.rune_18.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 Forward_DeathTrapsCrawl()
  game.UI.LoadCheck("Cal720_LowerCenterRoom")
  game.FindLevel("Cal720_LowerCenterRoom"):GetGameObject("Cal720_Banter"):CallScript("DeathTraps_Crawl")
end
function DisableAllCA()
  DisableCrawls()
  GameObjects.ObserveSap.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()
    GameObjects.CombatCA5.LuaObjectScript.Disable()
    GameObjects.CombatCA6.LuaObjectScript.Disable()
    GameObjects.CombatCA7.LuaObjectScript.Disable()
  end
end
function MakeNervous()
  game.AI.FindSon():CallScript("EnterBehaviorContext", "NERVOUS_BEHAVIOR_CONTEXT_CONFIG")
end
function ClearNervous()
  game.AI.FindSon():CallScript("ClearBehaviorContext")
end
function AbortTryptich()
  local cal720 = game.FindLevel("Cal720_LowerCenterRoom")
  if cal720 ~= nil then
    cal720:CallScript("DisableTryptich")
  end
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("FinalCheckRight") then
    son:Warp(GameObjects.crawl1_InstantExit_pos:GetWorldPosition(), GameObjects.crawl1_InstantExit_pos:GetWorldForward())
  end
end
