local LD = require("design.LevelDesignLibrary")
local timer = require("level.timer")
local uiCalls = require("ui.uicalls")
local checkpoint = require("level.checkpoint")
local TUT = require("game.GlobalTutorials")
local thisLevel
local isGateOpening = false
local entered200FirstTime = false
local player, son
local warpoffset = engine.Vector.New(0, 0, -2)
function OnScriptLoaded(level)
  SoundInit()
  thisLevel = level
  player = game.Player.FindPlayer()
  son = game.AI.FindSon()
  GameObjects.SwitchWall_190.LuaObjectScript.OverrideCameraInteractApproach("ENV_Interact_WallSwitch_LS_Wide")
  GameObjects.SwitchWall_190.LuaObjectScript.SetCameraApproachPitch(13)
  GameObjects.SwitchWall_190.LuaObjectScript.OverrideCameraSubmissionTime(4)
  GameObjects.SwitchWall_200.LuaObjectScript.OverrideCameraInteractApproach("ENV_Interact_WallSwitch_RS_Wide")
  GameObjects.SwitchWall_200.LuaObjectScript.SetCameraApproachPitch(13)
  GameObjects.SwitchWall_200.LuaObjectScript.OverrideCameraSubmissionTime(4)
  game.Compass.SetGatewayMarkerIsOpen("PP_200_Helper8", true)
end
function OnFirstStart(level)
  GameObjects.EntZn_Return_MainZone:HideEntityVolume()
  GameObjects.TraversePath_Squeeze1:HideTraversePath()
end
function OnStart(level)
  if game.Level.GetVariable("CompletedCineNumber") > 263 then
    GameObjects.IdleContextZone_Puzzled.LuaObjectScript.Disable()
  end
  if game.Level.GetVariable("CompletedCineNumber") > 310 then
    GameObjects.Son_RopeDrop1.LuaObjectScript.Enable()
    GameObjects.Son_RopeDrop2.LuaObjectScript.Enable()
  end
  if game.Level.GetVariable("CompletedCineNumber") >= 450 then
    game.Compass.SetGatewayMarkerIsOpen("PP_obj250", false)
  end
  SoundOnStart()
  if GameObjects.Gate_Entrance.AnimFrame == 0 then
    isGateOpening = false
    GameObjects.SwitchWall_190.LuaObjectScript.Enable()
    GameObjects.SwitchWall_200.LuaObjectScript.Enable()
    if GameObjects.SwitchWall_200.LuaObjectScript.SwitchIsBeingTurnedOn() == true then
      GameObjects.SwitchWall_200.LuaObjectScript.ToggleState()
    end
    if GameObjects.SwitchWall_200.LuaObjectScript.SwitchIsBeingTurnedOn() == true then
      GameObjects.SwitchWall_200.LuaObjectScript.ToggleState()
    end
  end
end
function Zone_GateEntranceClose_Exit()
  if player:InsideZone(GameObjects.Zone_GateEntranceClose) == false and son:InsideZone(GameObjects.Zone_GateEntranceClose) == false then
    GateEntrance_Close()
  end
end
function BrokenLantern_SonUnavailable200()
  GameObjects.LiftDoor_Gate_StaysOpen.LuaObjectScript.SetAllowSyncWithSonNotAvailable(true)
  GameObjects.LiftDoor_Gate_StaysOpen.LuaObjectScript.GetInteractZone():SetRequiresSonUnoccupied(false)
end
function BrokenLantern_SonAvailable200()
  GameObjects.LiftDoor_Gate_StaysOpen.LuaObjectScript.GetInteractZone():SetRequiresSonUnoccupied(true)
  GameObjects.LiftDoor_Gate_StaysOpen.LuaObjectScript.SetAllowSyncWithSonNotAvailable(false)
end
function RopeDrop_Enable()
  GameObjects.Son_RopeDrop1.LuaObjectScript.EnablePlayerInteract()
end
function ShimmyBreakAll()
  LD.BreakObject(GameObjects.ShimmyBreak01)
  LD.BreakObject(GameObjects.ShimmyBreak03)
  LD.BreakObject(GameObjects.ShimmyBreak04)
  LD.BreakObject(GameObjects.ShimmyBreak05)
  GameObjects.TraversePath_Squeeze1:ShowTraversePath()
end
function ClusterBackMidBreakAll()
  LD.BreakObject(GameObjects.ClusterBackMid01)
  LD.BreakObject(GameObjects.ClusterBackMid02)
  LD.BreakObject(GameObjects.ClusterBackMid03)
end
function ClusterBackBreakAll()
  LD.BreakObject(GameObjects.ClusterBackBreak01)
  LD.BreakObject(GameObjects.ClusterBackBreak02)
  LD.BreakObject(GameObjects.ClusterBackBreak03)
end
function ClusterLeftBreakAll()
  LD.BreakObject(GameObjects.ClusterBackLeft01)
  LD.BreakObject(GameObjects.ClusterBackLeft02)
  LD.BreakObject(GameObjects.ClusterBackLeft03)
end
function LoadCheckPeak203()
  game.UI.LoadCheck("Peak203_ChiselSite")
end
function LoadCheckPeak200()
  game.UI.LoadCheck("Peak200_ChimneyLow")
  game.UI.LoadCheck("Peak200_ChimneyLowVista")
  game.UI.LoadCheck("Peak210_RollerRoomLH")
  game.UI.LoadCheck("Peak080_Global")
end
function LoadCheckPeak190()
  game.UI.LoadCheck("Peak190_ChimneyEnter")
end
function LoadCheckPeak210()
  game.UI.LoadCheck("Peak080_Global")
  game.UI.LoadCheck("Peak580_ExpressElevator")
  game.UI.LoadCheck("Peak210_RollerRoomLH")
  game.UI.LoadCheck("Peak190_ChimneyEnter")
end
function LoadCheckPeak260()
  game.UI.LoadCheck("Peak260_ChimneyLowHall")
end
function LoadCheckPeak580()
  game.UI.LoadCheck("Peak580_ExpressElevator")
end
function Zone_Btr_CartPeak_Disable()
  GameObjects.Btr_CartPeak:HideEntityVolume()
  print("DISABLE ZONE FOR CART PEAK")
end
function SCA_SecretShimmyEnter_Enable()
  GameObjects.SCA_SecretShimmyEnter.LuaObjectScript.Enable()
end
function SCA_SecretShimmyExit_Enable()
  GameObjects.SCA_SecretShimmyExit.LuaObjectScript.Enable()
end
function SCA_RopeDown1_Down_Enable()
  GameObjects.SCA_RopeDown1_Down.LuaObjectScript.Enable()
end
function SCA_RopeDown1_Up_Enable()
  GameObjects.SCA_RopeDown1_Up.LuaObjectScript.Enable()
end
function SCA_RopeDown2_Down_Enable()
  GameObjects.SCA_RopeDown2_Down.LuaObjectScript.Enable()
end
function SCA_RopeDown2_Up_Enable()
  GameObjects.SCA_RopeDown2_Up.LuaObjectScript.Enable()
end
function SCA_ChiselDoor200_Enable()
  GameObjects.SCA_ChiselDoor203.LuaObjectScript.Disable()
  GameObjects.SCA_ChiselDoor200.LuaObjectScript.Enable()
end
function SCA_SCA_ChiselDoor203_Enable()
  GameObjects.SCA_ChiselDoor200.LuaObjectScript.Disable()
  GameObjects.SCA_ChiselDoor203.LuaObjectScript.Enable()
end
function IdleContextZone_Switch()
  GameObjects.IdleContextZone_Puzzled.LuaObjectScript.Disable()
  GameObjects.Zone_IdleContext_Puzzled:HideEntityVolume()
  timer.StartLevelTimer(2, function()
    game.AI.FindSon():CallScript("EnterBehaviorContext", "WAIT_AND_EXPLORE_BEHAVIOR_CONTEXT_CONFIG")
  end)
end
function Objective101_End_Delay()
  LD.CompleteQuest("Quest_PeaksPass_Objective101")
end
function LowerBridgeFront()
  GameObjects.BridgeFront:PlayAnimToEnd()
end
function bladesTnF()
  game.Level.SetVariable("BladeInteract", true)
end
function BurnableCoffinActivate()
  GameObjects.coffin_tier4_peak200_1.LuaObjectScript.Enable()
end
function BlastWallOFF()
  GameObjects.BlastWall:HideCollision()
end
function GateEntrance_Open()
  if isGateOpening == false then
    isGateOpening = true
    local peak190 = game.FindLevel("Peak190_ChimneyEnter")
    if peak190 ~= nil then
      peak190:GetGameObject("POI_FirstSawClaw"):CallScript("ShowEntityZones")
    end
    GameObjects.Gate_Entrance:PlayAnimToEnd()
    PlaySoundOnStart()
    CameraShakeGateEntrance()
    GameObjects.SwitchWall_200.LuaObjectScript.SetIsInteracting(true)
    GameObjects.SwitchWall_190.LuaObjectScript.SetIsInteracting(true)
    if GameObjects.SwitchWall_190.LuaObjectScript.IsSwitchEnabled() == true then
      GameObjects.SwitchWall_190.LuaObjectScript.Disable()
      GameObjects.SwitchWall_190.LuaObjectScript.ToggleState()
    end
    if GameObjects.SwitchWall_200.LuaObjectScript.IsSwitchEnabled() == true then
      GameObjects.SwitchWall_200.LuaObjectScript.Disable()
      GameObjects.SwitchWall_200.LuaObjectScript.ToggleState()
    end
    local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
    if 450 <= completedCineNumber then
      GameObjects.EntZn_Return_MainZone:ShowEntityVolume()
    end
  end
end
function GateEntrance_Close()
  if isGateOpening == true then
    isGateOpening = false
    local peak190 = game.FindLevel("Peak190_ChimneyEnter")
    if peak190 ~= nil then
      peak190:GetGameObject("POI_FirstSawClaw"):CallScript("HideEntityZones")
    end
    GameObjects.Gate_Entrance:PlayAnimationToFrame(0, {Rate = -1.5})
    PlaySoundOnStart()
    CameraShakeGateEntrance()
    GameObjects.SwitchWall_200.LuaObjectScript.SetIsInteracting(false)
    GameObjects.SwitchWall_190.LuaObjectScript.SetIsInteracting(false)
    GameObjects.SwitchWall_190.LuaObjectScript.ToggleState()
    GameObjects.SwitchWall_200.LuaObjectScript.ToggleState()
    GameObjects.SwitchWall_190.LuaObjectScript.Enable()
    GameObjects.SwitchWall_200.LuaObjectScript.Enable()
  end
end
function CameraShakeGateEntrance()
  game.Blender.Trigger({
    Name = "FSE_SHAKE_SLIDING_OBJECT_HEAVY",
    Duration = 2.69,
    TweenIn = {Time = 0},
    TweenOut = {Time = 0.39},
    Weight = 0.8
  })
  game.Blender.Trigger({
    Name = "FFB_GENERIC_RUMBLE_MEDIUM",
    Duration = 2.69,
    TweenIn = {Time = 0},
    TweenOut = {Time = 0.39},
    Priority = 2
  })
end
function PlayShakeEffect()
  local effect = {
    EffectName = "FSE_SHAKE_JAMMED",
    Duration = 0.8,
    TweenInTime = 0.08,
    TweenOutTime = 0.07
  }
  game.FX.SubmitEffect(effect)
end
function EnableCorpseInteract()
  GameObjects.corpse_rare_tier1_peak200_1.LuaObjectScript.Enable()
end
function AnimateTrilobytes01()
  GameObjects.TrilobyteGroup_01:PlayAnimToEnd()
  PlaySoundTrilobyteScurry01()
  GameObjects.TrilobyteEntZoneGroup:Hide()
end
function AnimateTrilobytes02()
  GameObjects.TrilobyteGroup_02:PlayAnimToEnd()
  PlaySoundTrilobyteScurry02()
  GameObjects.TrilobyteEntZoneGroup1:Hide()
end
function AnimateTrilobytes03()
  GameObjects.TrilobyteGroup_03:PlayAnimToEnd()
  PlaySoundTrilobyteScurry03()
  GameObjects.TrilobyteEntZoneGroup2:Hide()
end
function Btr_RopeStuckC_Disable()
  GameObjects.Btr_RopeStuckC:HideEntityVolume()
end
function Trigger_Out_Of_Bounds()
  player:AddMarker("Out_Of_Bounds")
end
function Trigger_In_Bounds()
  player:RemoveMarker("Out_Of_Bounds")
end
function SonWarpSafe_200()
  timer.StartLevelTimer(0.1, function()
    GameObjects.SonWarpSafe_200.LuaObjectScript.WarpSon()
    print("WARP SON 200")
  end)
end
function CA_Observe_RuneRead_Disable()
  local peak080 = game.FindLevel("peak080_Global")
  peak080:CallScript("CA_Observe_RuneRead_Disable_080")
end
function Peak080_ExitDoor_SCA_Disable()
  local peak080 = game.FindLevel("peak080_Global")
  peak080:CallScript("SCA_TrackInvestigate_Disable")
  peak080:CallScript("SCA_ClawInvestigate_Disable")
end
function OnAttached_RecenterEntering200()
  game.Camera.Recenter({
    TimeStart = 0,
    TimeDuration = 2.4,
    LockRecenter = 0.8,
    YawRange = -1,
    TriggerLeft = 0,
    ReturnLeft = -18,
    ReturnRight = -19,
    TriggerRight = 0,
    PitchRange = -1,
    TriggerUp = 0,
    ReturnUp = 12,
    ReturnDown = 11,
    TriggerDown = 0
  })
end
function OnAttached_RecenterExiting200()
  game.Camera.Recenter({
    TimeStart = 0,
    TimeDuration = 2.4,
    LockRecenter = 0.8,
    YawRange = -1,
    TriggerLeft = 0,
    ReturnLeft = 15,
    ReturnRight = 14,
    TriggerRight = 0,
    PitchRange = -1,
    TriggerUp = 0,
    ReturnUp = 12,
    ReturnDown = 11,
    TriggerDown = 0
  })
end
function DebugSonWarp()
  game.AI.FindSon():Warp(player:GetWorldPosition() + warpoffset, player:GetWorldForward())
end
function CancelMsg()
  uiCalls.UI_Event_TurnOffDesignerMessage()
end
function ZoneReportLowChimney()
  uiCalls.UI_Event_DiscoverLocation("Belly of the Mountain")
  LD.SetRegionDiscovered("Peakspass")
  entered200FirstTime = true
end
function ChangePeak200Phase()
  game.Level.SetVariable("PEAK_ChimneyPhase", 2)
end
function OnEvaluateLoadGroup_AIWads()
  if game.Level.GetVariable("PEAK_ChimneyPhase") == 1 and game.Level.GetVariable("CompletedCineNumber") < 450 then
    return "AIWadsFirstEntry"
  elseif game.Level.GetVariable("PEAK_ChimneyPhase") == 2 and game.Level.GetVariable("CompletedCineNumber") < 450 then
    return "AIWadsRoller"
  elseif game.Level.GetVariable("CompletedCineNumber") >= 450 then
    return "AIWadsReturn"
  end
end
function OnSaveCheckpoint(level)
  return {
    levelstate = checkpoint.Save(),
    isGateOpening = isGateOpening,
    entered200FirstTime = entered200FirstTime
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  checkpoint.Restore(savedInfo.levelstate)
  isGateOpening = savedInfo.isGateOpening
  entered200FirstTime = savedInfo.entered200FirstTime
end
function Peak200_CraneCartPuzzleSolved()
  GameObjects.LiftDoor_Gate_StaysOpen:PlayAnimToEnd()
  GameObjects.Son_RopeDrop3.LuaObjectScript.ActivateRopeDrop()
  GameObjects.Son_RopeDrop3.Child.LuaObjectScript.Disable()
  GameObjects.CombatScripts.LuaObjectScript.DisableFirstVisitFights()
  GameObjects.Zone_PopcornEnemyAttack5:HideEntityVolume()
end
function Complete_Quest_Caldera_Objective610()
  LD.CompleteQuest("Quest_Caldera_Objective610")
end
function ShowObjective800_UI()
  uiCalls.UI_Event_SendMsgToQuestLog({
    Category = 10250,
    Header = 1418,
    Body = 21330,
    MessageType = tweaks.tQuestUiMessage.eMessageType.kQMS_Default,
    Quest = "Quest_PeaksPass_Objective800"
  })
end
function EnableChiselMarker()
  LD.SetMarkerState("PP_200_ChiselEntrance", 1)
  LD.UpdateMap("PP_200_ChiselEntrance", 0)
  ChiselQuest()
end
function DisableChiselMarker()
  LD.SetMarkerState("PP_200_ChiselEntrance", 0)
end
function ChiselQuest()
  local questState = game.QuestManager.GetQuestState("Quest_Labor_ChiselDungeon_Find_Peaks")
  if questState ~= "Complete" then
    LD.ActivateQuest("Quest_Labor_ChiselDungeons_Parent")
    LD.CompleteQuest("Quest_Labor_ChiselDungeon_Find_Peaks")
    game.QuestManager.IncrementQuestProgress("Quest_Labor_ChiselDungeon_Find", 1)
  end
end
local soundEmitter
local gateSoundEvents = {
  isLooping = true,
  OnLoop = "SND_DOOR_Gate_Wooden_Lift_Narrow_LP",
  OnStop = "SND_DOOR_Gate_Wooden_Lift_Narrow_Latch"
}
local chiselDoorSoundOverride = {
  OnInteractForward_Left = "SND_DOOR_Wood_Double_Pry_Apart_Seq_L",
  OnInteractForward_Right = "SND_DOOR_Wood_Double_Pry_Apart_Seq_R",
  OnInteractBackward_Left = "SND_DOOR_Wood_Double_Pry_Apart_Seq_L",
  OnInteractBackward_Right = "SND_DOOR_Wood_Double_Pry_Apart_Seq_R"
}
local soundTrilobyteEmitters01 = {}
local soundTrilobyteEmitters02 = {}
local soundTrilobyteEmitters03 = {}
function SoundInit()
  soundEmitter = GameObjects.Gate_Entrance:FindSingleSoundEmitterByName("SNDGate_Entrance")
  soundTrilobyteEmitters01 = GameObjects.TrilobyteGroup_01.SoundEmitters
  soundTrilobyteEmitters02 = GameObjects.TrilobyteGroup_02.SoundEmitters
  soundTrilobyteEmitters03 = GameObjects.TrilobyteGroup_03.SoundEmitters
end
function SoundOnStart()
  GameObjects.ChiselDoor_Pro.Child:FindSingleGOByName("SpreadDoor_Pro").Child.LuaObjectScript.SoundSetup(chiselDoorSoundOverride)
end
function PlaySoundOnStart()
  LD.PlaySound(soundEmitter, gateSoundEvents.OnLoop)
  GameObjects.Gate_Entrance:OnAnimDone(thisLevel, "PlaySoundOnStop")
end
function PlaySoundOnStop()
  LD.StopSound(soundEmitter, gateSoundEvents.OnLoop)
  LD.PlaySound(soundEmitter, gateSoundEvents.OnStop)
end
function PlaySoundTrilobyteScurry01()
  PlaySoundTrilobyteScurry(soundTrilobyteEmitters01)
end
function PlaySoundTrilobyteScurry02()
  PlaySoundTrilobyteScurry(soundTrilobyteEmitters02)
end
function PlaySoundTrilobyteScurry03()
  PlaySoundTrilobyteScurry(soundTrilobyteEmitters03)
end
function PlaySoundTrilobyteScurry(emitters)
  for _, v in ipairs(emitters) do
    LD.PlaySound(v, "SND_AMB_EMIT_Bats_Squeak_OneOff")
  end
end
function idleMusic()
  game.Audio.StartMusic("SND_MX_TRANS_TO_IDLE")
end
function restoreMusic()
  local peak050 = game.FindLevel("Peak050_Sound")
  if peak050 ~= nil and game.Level.GetVariable("CompletedCineNumber") >= 610 then
    peak050:CallScript("revisitMusic")
  end
end
function ShowDebugTable()
  local debugTable = {}
  debugTable.Title = "Door Info"
  debugTable.X = 120
  debugTable.Y = 10
  debugTable.TitleColor = engine.Vector.New(255, 0, 128)
  debugTable[#debugTable + 1] = {
    "AnimFrame: ",
    GameObjects.Gate_Entrance.AnimFrame
  }
  engine.DrawDebugTable(debugTable)
end
