local LD = require("design.LevelDesignLibrary")
local timers = require("level.timer")
local checkpoint = require("level.checkpoint")
local CWU = require("camera.camera_wakeup")
local TUT = require("game.GlobalTutorials")
local monitors = require("level.MonitorLibrary")
local uiCalls = require("ui.uicalls")
local thisLevel, camWakeUpLevel, ropeBridge, BridgeCollision
local bridgeVibrateDestroyed = false
local bridgeBlockerVibrateDestroyed = false
local bridgeFirstFallAnimFrame = 36
local bridgeFallen = false
local sCA_BridgeHintTimer01, sCA_BridgeHintTimer02, axePinFreezeFx, axeIceRecallFx
local hiddenCrystalSeen = false
local pullyStuck = true
function OnScriptLoaded(level)
  thisLevel = level
  camWakeUpLevel = level
  BridgeCollision = GameObjects.BridgeCollision
  ropeBridge = GameObjects.collapsingBridge00_P.Child
  local lockCollision = GameObjects.MachineAxeCollision
  lockCollision.LuaObjectScript.SetSaveAxeState(true)
  lockCollision.LuaObjectScript.RegisterOnWeaponEmbed(FreezeGears)
  lockCollision.LuaObjectScript.RegisterOnWeaponUnembed(UnfreezeGears)
  lockCollision.LuaObjectScript.RegisterOnWeaponUnembedStart(UnfreezeGearsStart)
  axePinFreezeFx = GameObjects.FrozenRoot_freezeFX
  axeIceRecallFx = GameObjects.FrozenRoot_recallFX
  sCA_BridgeHintTimer01 = timers.StartLevelTimer(30, GameObjects.Peak720_Banter.LuaObjectScript.BlastBridge_Hint_Banter)
  sCA_BridgeHintTimer01:Stop()
  sCA_BridgeHintTimer02 = timers.StartLevelTimer(30, GameObjects.Peak720_Banter.LuaObjectScript.BlastBridge_Hint2_Banter)
  sCA_BridgeHintTimer02:Stop()
  local vibratecrankRJ = level:FindGameObject("WheelCrank01")
  if vibratecrankRJ ~= nil and vibratecrankRJ.LuaObjectScript ~= nil then
    vibratecrankRJ.LuaObjectScript.OverrideCameraInteractApproach("ENV_Crank_Approach_VibrateBasket_RJ")
  end
end
function OnFirstStart(level)
  ropeBridge:StartAnim("collapsingBridge_Fall_HiToLo")
  ropeBridge:JumpAnimToPercent(0)
  ropeBridge:PauseAnim()
  GameObjects.WheelCrank02.LuaObjectScript.Lock()
  GameObjects.NavObstacle_Bridge:HideNavObstacle()
  GameObjects.Zone_1stCrystalHint01Banter:HideEntityVolume()
  GameObjects.Zone_1stCrystalHint02Banter:HideEntityVolume()
  GameObjects.Zone_BlastBridgeIntroBanter:HideEntityVolume()
  GameObjects.Zone_BridgeHint01Banter:HideEntityVolume()
  GameObjects.Zone_BridgeHint02Banter:HideEntityVolume()
  GameObjects.TraverseLink_MantleSecret:HideTraverseLink()
  GameObjects.TraverseLink_MantleFront:HideTraverseLink()
  LD.HideFX(axePinFreezeFx)
  axePinFreezeFx:HideModel()
  LD.HideFX(axeIceRecallFx)
  axeIceRecallFx:HideModel()
end
function OnStart(level)
  SoundOnStart()
  GameObjects.WheelCrank01.LuaObjectScript.RegisterLockedAttemptCallback(function()
    if pullyStuck == true then
      GameObjects.Peak720_Banter.LuaObjectScript.FirstRechargingCrystal_Intro_Banter()
    end
    if hiddenCrystalSeen == false then
      GameObjects.Peak720_Banter.LuaObjectScript.FirstRechargingCrystal_Intro2_Banter()
    end
  end)
  if GameObjects.MachineAxeCollision:IsAxeEmbedded() == false then
    LD.HideFX(axePinFreezeFx)
    axePinFreezeFx:HideModel()
    LD.HideFX(axeIceRecallFx)
    axeIceRecallFx:HideModel()
  else
    LD.ShowFX(axePinFreezeFx)
    LD.HideFX(axeIceRecallFx)
    axeIceRecallFx:HideModel()
  end
end
function OnSaveCheckpoint(level)
  return {
    levelstate = checkpoint.Save(),
    bridgeVibrateDestroyed = bridgeVibrateDestroyed,
    bridgeBlockerVibrateDestroyed = bridgeBlockerVibrateDestroyed,
    hiddenCrystalSeen = hiddenCrystalSeen,
    pullyStuck = pullyStuck,
    bridgeFallen = bridgeFallen
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  checkpoint.Restore(savedInfo.levelstate)
  bridgeVibrateDestroyed = savedInfo.bridgeVibrateDestroyed
  bridgeBlockerVibrateDestroyed = savedInfo.bridgeBlockerVibrateDestroyed
  hiddenCrystalSeen = savedInfo.hiddenCrystalSeen
  pullyStuck = savedInfo.pullyStuck
  bridgeFallen = savedInfo.bridgeFallen
end
function SonSyncOff()
end
function SonSyncOn()
end
function ExitClimbToLower_SCA_ToggleOFF()
  GameObjects.SCA_FirstTripEntrance_ClimbExit.LuaObjectScript.Enable()
  GameObjects.SCA_FirstTripEntrance_Crossroads1.LuaObjectScript.Disable()
end
function EnterClimbToMiddle_SCA_ToggleON()
  GameObjects.SCA_FirstTripEntrance_ClimbExit.LuaObjectScript.Disable()
  GameObjects.SCA_FirstTripEntrance_Crossroads1.LuaObjectScript.Disable()
  GameObjects.SCA_VibrateCollapseTop.LuaObjectScript.Disable()
  local liftSlabBreakable = thisLevel:FindSingleGameObject("Vib_720_03_break")
  if liftSlabBreakable ~= nil then
    liftSlabBreakable = liftSlabBreakable.Child:GetBreakable()
    if liftSlabBreakable.Broken == false then
      if pullyStuck == true then
        GameObjects.CombatScripts.LuaObjectScript.CheckPosessComplete()
      else
        GameObjects.SCA_VibrateLift_Wait.LuaObjectScript.Enable()
      end
    end
    if liftSlabBreakable.Broken == true then
      GameObjects.SCA_PostVibrateCart_Wait.LuaObjectScript.Enable()
    end
  end
end
function DestroyVibrateLift_SCA_ToggleOFF()
  GameObjects.SCA_VibrateLift_Wait.LuaObjectScript.Disable()
  GameObjects.CA_observe_on_alert_preCombat.LuaObjectScript.Disable()
  GameObjects.SCA_PostVibrateCart_Wait.LuaObjectScript.Enable()
end
function ExitClimbToMiddle_SCA_ToggleOFF()
  GameObjects.SCA_VibrateLift_FireReady.LuaObjectScript.Disable()
  GameObjects.CA_observe_on_alert_preCombat.LuaObjectScript.Disable()
  GameObjects.SCA_VibrateLift_Wait.LuaObjectScript.Disable()
  GameObjects.SCA_PostVibrateCart_Wait.LuaObjectScript.Disable()
end
function SCA_PostVibrateCart_Wait_Enable()
  GameObjects.SCA_PostVibrateCart_Wait.LuaObjectScript.Enable()
end
function SCA_PostVibrateCart_Wait_Disable()
  GameObjects.SCA_PostVibrateCart_Wait.LuaObjectScript.Disable()
end
function PostClimbVibrateCollapseSlab()
  SCA_PostVibrateCart_Wait_Disable()
  GameObjects.SCA_VibrateCollapseTop.LuaObjectScript.Enable()
end
function SCA_BridgeSecret_Wait_Enable()
  GameObjects.SCA_BridgeSecret_Wait.LuaObjectScript.Enable()
end
function SCA_BridgeSecret_Wait_Disable()
  GameObjects.SCA_BridgeSecret_Wait.LuaObjectScript.Interrupt()
  GameObjects.SCA_BridgeSecret_Wait.LuaObjectScript.Disable()
end
function SCA_CartSecret_Wait_Enable()
  GameObjects.SCA_CartSecret_Wait.LuaObjectScript.Enable()
end
function SCA_CartSecret_Wait_Disable()
  GameObjects.SCA_CartSecret_Wait.LuaObjectScript.Disable()
end
function VibratePullyStuck_Destroyed()
  Btr_HiddenCrystal_LookAt_Disable()
  GameObjects.ReactionStim_LiftVibrateExplode.LuaObjectScript.Trigger()
  GameObjects.BtrTimer_CrystalHint01.LuaObjectScript.Cancel()
  GameObjects.Zone_1stCrystalHint02Banter:ShowEntityVolume()
  GameObjects.HiddenCrystal_AimBlockerCollision:HideCollision()
  pullyStuck = false
  GameObjects.SCA_VibrateLift_FireReady.LuaObjectScript.Interrupt()
  GameObjects.SCA_VibrateLift_FireReady.LuaObjectScript.Disable()
  GameObjects.SCA_VibrateLift_Wait.LuaObjectScript.Enable()
  timers.StartLevelTimer(0.45, function()
    game.Blender.Trigger({
      Name = "FSE_SHAKE_GENERIC_MEDIUM",
      Duration = 1.3,
      TweenIn = {Time = 0},
      TweenOut = {Time = 0.2},
      Priority = 3000
    })
  end)
  timers.StartLevelTimer(0.45, function()
    game.Blender.Trigger({
      Name = "FFB_GENERIC_RUMBLE_MEDIUM",
      Duration = 1.3,
      TweenIn = {Time = 0},
      TweenOut = {Time = 0.2},
      Priority = 3000
    })
  end)
end
function PullCart_MantleFront_Enable()
  GameObjects.TraverseLink_MantleFront:ShowTraverseLink()
end
function PullCart_MantleFront_Disable()
  GameObjects.TraverseLink_MantleFront:HideTraverseLink()
end
function PullCart_MantleSecret_Enable()
  GameObjects.TraverseLink_MantleSecret:ShowTraverseLink()
end
function PullCart_MantleSecret_Disable()
  GameObjects.TraverseLink_MantleSecret:HideTraverseLink()
end
function ArrowToggleTutorial()
  TUT.ArrowToggle_Tutorial()
end
function DisableTutorialMessage()
  uiCalls.UI_Event_TurnOffDesignerMessage()
end
function HangLootBreak()
  GameObjects.LootBarrel:HideCollision()
end
function EnableCaveCrawl()
  GameObjects.PeaksPassCartCrank2.LuaObjectScript.Enable()
end
function EnableSonTranslate()
  GameObjects.QuestLoreMarker:FindSingleGOByName("GenericSonInteract").LuaObjectScript.Enable()
end
function VibrateChest1()
  GameObjects.Loot_LegendaryChest_Vibrate1.LuaObjectScript.Enable()
end
function WakeClimbScaffold010FWD()
  CWU.WakeUpTheRecenterZones("RCenter_WakeGroup_Scaffold010_Fwd", camWakeUpLevel)
end
function WakeClimbScaffold030FWD()
  CWU.WakeUpTheRecenterZones("RCenter_WakeGroup_Scaffold030_Fwd", camWakeUpLevel)
end
function BridgeFall()
  if bridgeBlockerVibrateDestroyed == false then
    LD.ForceAxeUnembed(GameObjects.MachineAxeCollision)
    bridgeVibrateDestroyed = true
    PlayBridgeFirstFall()
    ropeBridge:StartAnim("collapsingBridge_Fall_HiToMid")
    SetupRumbleFeedbackAndHideBridgeCollisionAtEnd(34, false)
    GameObjects.Peak720_Banter.LuaObjectScript.BlastBridge_GuessNot_Banter()
    BridgeHint01Disable()
    BridgeHint02Enable()
  else
    LD.ForceAxeUnembed(GameObjects.MachineAxeCollision)
    bridgeVibrateDestroyed = true
    ropeBridge:StartAnim("collapsingBridge_Fall_HiToLo")
    ropeBridge:OnAnimDone(thisLevel, "SetupCrankAtBottom")
    SetupRumbleFeedbackAndHideBridgeCollisionAtEnd(48, true)
    PlayBridgeCompleteFall()
    BridgeHint01Disable()
  end
end
function RemoveBridgeBlocker()
  if bridgeVibrateDestroyed == false then
    bridgeBlockerVibrateDestroyed = true
    BridgeHint02Disable()
  else
    LD.ForceAxeUnembed(GameObjects.MachineAxeCollision)
    bridgeBlockerVibrateDestroyed = true
    PlayBridgeSecondFall()
    ropeBridge:StartAnim("collapsingBridge_Fall_MidToLo")
    ropeBridge:OnAnimDone(thisLevel, "SetupCrankAtBottom")
    SetupRumbleFeedbackAndHideBridgeCollisionAtEnd(34, true)
    BridgeHint02Disable()
  end
end
function SetupCrankAtBottom()
  ropeBridge:ClearAllAnimCallbacks()
  ropeBridge:StartAnim("collapsingBridge_Lift_LoToHi_Linear")
  ropeBridge:PauseAnim()
  GameObjects.WheelCrank02.LuaObjectScript.SetDrivenObject(ropeBridge)
  GameObjects.WheelCrank02.LuaObjectScript.SetAnimSynchedObjects("Machine")
  GameObjects.WheelCrank02.LuaObjectScript.SetMaxStopCycle(2)
  GameObjects.WheelCrank02.LuaObjectScript.Unlock()
  bridgeFallen = true
  game.World.StoreCheckpoint()
end
function SetupRumbleFeedbackAndHideBridgeCollisionAtEnd(rumbleFrame, hideCollision)
  local feedbackM = monitors.CreateAnimFrameMonitor(ropeBridge)
  LD.AddControllerRumble({EffectName = "FFB_SMALL"})
  feedbackM:OnFrameForward(rumbleFrame, function()
    if hideCollision == true then
      BridgeCollision:HideCollision()
    end
    PlayBridgeHitFeedback(feedbackM)
  end)
end
function PlayBridgeHitFeedback(monitor)
  game.FX.StopEffect({EffectName = "FFB_SMALL"})
  if monitor ~= nil then
    monitor:Stop()
    monitor:Terminate()
    monitor = nil
  end
  LD.AddScreenShake({
    EffectName = "FSE_SHAKE_VIBRATE_CRYSTAL_INTACT"
  })
  LD.AddControllerRumble({EffectName = "FFB_GIANT", Duration = 2})
end
function FreezeGears()
  LD.ShowFX(axePinFreezeFx)
  LD.HideFX(axeIceRecallFx)
  axeIceRecallFx:HideModel()
  if bridgeFallen then
    GameObjects.WheelCrank02.LuaObjectScript.Lock()
    local crankCycle = GameObjects.WheelCrank02.LuaObjectScript.GetCurrentCycle()
    if crankCycle == 1 then
      BridgeCollision:ShowCollision()
    elseif crankCycle == 0 then
      BridgeCollision:HideCollision()
    end
  end
  PlaySoundFreezeMachine()
end
function UnfreezeGearsStart()
  LD.HideFX(axePinFreezeFx)
  axePinFreezeFx:HideModel()
  LD.ShowFX(axeIceRecallFx)
  axeIceRecallFx:OnAnimDone(thisLevel, "HideRecallFX")
  StopSoundUnfreezeMachine()
end
function UnfreezeGears()
  if bridgeFallen then
    GameObjects.WheelCrank02.LuaObjectScript.Unlock()
  end
end
function HideRecallFX()
  LD.HideFX(axeIceRecallFx)
  axeIceRecallFx:HideModel()
end
function WheelCrankAtStartEvent()
  GameObjects.NavObstacle_Bridge:ShowNavObstacle()
  GameObjects.SCA_BridgeSecret_Wait.LuaObjectScript.Enable()
  GameObjects.LeadTheWay_720LongHall.LuaObjectScript.Disable()
  PlaySoundOnBridgeCrankAtStart()
end
function WheelCrankAtEndEvent()
  BridgeCollision:HideCollision()
  GameObjects.NavObstacle_Bridge:HideNavObstacle()
  GameObjects.SCA_BridgeSecret_Wait.LuaObjectScript.Interrupt()
  GameObjects.SCA_BridgeSecret_Wait.LuaObjectScript.Disable()
  GameObjects.LeadTheWay_720LongHall.LuaObjectScript.Enable()
  PlaySoundOnBridgeCrankAtEnd()
end
function WheelCrankForward()
  PlaySoundOnBridgeCrankForward()
end
function WheelCrankBackward()
  PlaySoundOnBridgeCrankBackward()
end
function WheelCrankOnPause()
  PlaySoundOnBridgeCrankPause()
end
function WheelCrankOnRewind()
  PlaySoundOnBridgeCrankRewind()
end
function Endgame_Checkpoint()
  game.World.StoreCheckpoint()
end
function LoadCheck_Peak790()
  game.UI.LoadCheck("Peak790_ChimneyTopReturn")
end
function Btr_HiddenCrystal_LookAt_Disable()
  GameObjects.Btr_HiddenCrystal_LookAt:HideEntityVolume()
end
function CrystalHint01Enable()
  GameObjects.Zone_1stCrystalHint01Banter:ShowEntityVolume()
  hiddenCrystalSeen = true
end
function CrystalHint02Disable()
  GameObjects.BtrTimer_CrystalHint02.LuaObjectScript.Cancel()
end
function BridgeHint01Enable()
  GameObjects.Zone_BridgeHint01Banter:ShowEntityVolume()
end
function BridgeHint01Disable()
  GameObjects.Zone_BridgeHint01Banter:HideEntityVolume()
end
function BridgeHint02Enable()
  GameObjects.Zone_BridgeHint02Banter:ShowEntityVolume()
end
function BridgeHint02Disable()
  GameObjects.Zone_BridgeHint02Banter:HideEntityVolume()
end
function OnEvaluateLoadGroup_AIWads()
  if game.Level.GetVariable("CompletedCineNumber") < 450 then
    return "AIWadsFirstEntry"
  elseif game.Level.GetVariable("CompletedCineNumber") >= 450 then
    return "AIWadsReturn"
  end
end
function Peak720_FirstVisitTopAndMidDone()
  GameObjects.Vibrate02_Setup.LuaObjectScript.Vibrate02SetupSolve()
  BridgeCollision:HideCollision()
  GameObjects.Vibrate_RockBridge2:Hide()
  GameObjects.Vibrate_RockBridge2:HideCollision()
  GameObjects.CombatScripts.LuaObjectScript.DisableFirstVisitMidAndTopFights()
end
function Peak720_FirstVisitBottom()
  GameObjects.CombatScripts.LuaObjectScript.DisableFirstVisitBottomFight()
  GameObjects.Vibrate_CaveCrawl:Hide()
  GameObjects.Vibrate_CaveCrawl:HideCollision()
  GameObjects.PullCrate:JumpAnimToFrame(GameObjects.PullCrate.AnimLengthFrames)
  EnableCaveCrawl()
end
local machinerySoundEmitter
local machinerySoundLoop = "SND_MECH_Crank_Bridge_Gears_Peak720_LP"
local machineryStopSound = "SND_MECH_Crank_Bridge_Gears_Peak720_STOP"
local spindleSoundEmitter
local spindleSoundLoop = "SND_MECH_Crank_Bridge_Spindle_Peak720_LP"
local BridgeSounds = {
  FirstFall = "SND_MECH_Wooden_Bridge_Collapse1_Peak740",
  SecondFall = "SND_MECH_Wooden_Bridge_Collapse2_Peak740",
  CompleteFall = "SND_MECH_Wooden_Bridge_Collapse3_Peak740",
  SlamUp = "SND_MECH_Wood_Bridge_Slam_Up",
  SlamDown = "SND_MECH_Wood_Bridge_Slam_Down"
}
local BridgeDrivenObjectOverrides = {
  SoundEmitter = nil,
  OnForward = "SND_MECH_Wood_Bridge_Crank_Up",
  OnBackward = "SND_MECH_Wood_Bridge_Crank_Down",
  OnFastForward = "SND_MECH_Wood_Bridge_Release_LP",
  OnRewind = "SND_MECH_Wood_Bridge_Release_LP"
}
local PushCartSounds = {
  OnForward = "SND_MECH_Wooden_Cart_PushPull_720_LP",
  OnBackward = "SND_MECH_Wooden_Cart_PushPull_720_LP"
}
function SoundOnStart()
  machinerySoundEmitter = GameObjects.Machine:FindSingleGOByName("SNDGrpBridgeMachinery").SoundEmitters[1]
  spindleSoundEmitter = GameObjects.SNDGrpBridgeSpindle.SoundEmitters[1]
  BridgeDrivenObjectOverrides.SoundEmitter = ropeBridge.SoundEmitters[1]
  GameObjects.WheelCrank02.LuaObjectScript.DrivenObjectSoundSetup(BridgeDrivenObjectOverrides)
  GameObjects.QuestLoreMarker:FindSingleGOByName("pSonReadRune").LuaObjectScript.LoreMarkerRuneReadSoundSetup()
  GameObjects.PeaksPassCartCrank2.LuaObjectScript.CrankSoundSetup(PushCartSounds)
  if game.Level.GetVariable("CompletedCineNumber") < 460 then
    GameObjects.HangingHazard_CutRope1:Hide()
    GameObjects.HangingHazard_CutRope2:Hide()
    GameObjects.HangingHazard_CutRope4:Hide()
  else
    GameObjects.HangingHazard_CutRope1:Show()
    GameObjects.HangingHazard_CutRope2:Show()
    GameObjects.HangingHazard_CutRope4:Show()
  end
end
function PlaySoundOnBridgeCrankAtStart()
  StopSoundActiveLoops()
  PlaySoundBridgeSlamUp()
end
function PlaySoundOnBridgeCrankAtEnd()
  StopSoundActiveLoops()
  PlaySoundBridgeSlamDown()
end
function PlaySoundOnBridgeCrankForward()
  PlaySoundActiveLoops()
end
function PlaySoundOnBridgeCrankBackward()
  PlaySoundActiveLoops()
end
function PlaySoundOnBridgeCrankPause()
  StopSoundActiveLoops()
end
function PlaySoundOnBridgeCrankRewind()
  PlaySoundActiveLoops()
end
function PlaySoundActiveLoops()
  LD.PlaySound(machinerySoundEmitter, machinerySoundLoop)
  LD.PlaySound(spindleSoundEmitter, spindleSoundLoop)
end
function StopSoundActiveLoops()
  LD.StopSound(machinerySoundEmitter, machineryStopSound, true)
  LD.StopSound(machinerySoundEmitter, machinerySoundLoop)
  LD.StopSound(spindleSoundEmitter, spindleSoundLoop)
end
function PlayBridgeFirstFall()
  LD.PlaySound(BridgeDrivenObjectOverrides.SoundEmitter, BridgeSounds.FirstFall)
end
function PlayBridgeSecondFall()
  LD.PlaySound(BridgeDrivenObjectOverrides.SoundEmitter, BridgeSounds.SecondFall)
end
function PlayBridgeCompleteFall()
  LD.PlaySound(BridgeDrivenObjectOverrides.SoundEmitter, BridgeSounds.CompleteFall)
end
function PlaySoundBridgeSlamUp()
  LD.PlaySound(BridgeDrivenObjectOverrides.SoundEmitter, BridgeSounds.SlamUp)
end
function PlaySoundBridgeSlamDown()
  LD.PlaySound(BridgeDrivenObjectOverrides.SoundEmitter, BridgeSounds.SlamDown)
end
function PlaySoundFreezeMachine()
  LD.PlaySound(machinerySoundEmitter, "SND_WPN_Axe_Hit_Freeze_Object_LP")
end
function StopSoundUnfreezeMachine()
  LD.StopSound(machinerySoundEmitter, "SND_WPN_Axe_Hit_Freeze_Object_LP")
end
