local ND = require("design.NarrativeDesignLibrary")
local LD = require("design.LevelDesignLibrary")
local actor = require("narrative.actor")
local thisObj, thisLevel, kraActor, sonActor, brokActor, bldrActor, cineLights
local startFrame = 0
local warpFlashStartPercent = 0.9665
local warpFlashParams = {
  EffectName = "FSE_HENGEDISRUPTION_FLASH",
  Duration = 1,
  TweenInTime = 1.7,
  TweenOutTime = 1.2
}
local warpFogStartPercent = 0.9598
local warpFogParams = {
  EffectName = "FSE_HENGEDISRUPTION_FOG",
  Duration = 2,
  TweenInTime = 2,
  TweenOutTime = 0.8
}
function OnScriptLoaded(level, obj)
  thisObj = obj
  thisLevel = level
  InitializeVariables()
  game.SubObject.Sleep(obj)
  game.SubObject.SetForgetOnCheckpoint(obj)
end
function OnStart(level, obj)
  cineLights = GameObjects.Cine_Start_490
  HideCineLights()
  if CanSeqFire() then
    SetupCineSequence()
  end
end
function InitializeVariables()
  if CanSeqFire() then
    SetupActors()
  end
end
function SpawnBrok()
  local jointFace = thisObj:GetWorldJointForward(thisObj:GetJointIndex("Brok_StartJoint"))
  local jointPos = thisObj:GetWorldJointPosition(thisObj:GetJointIndex("Brok_StartJoint"))
  return game.AI.Spawn(thisLevel, jointPos, jointFace, "CRT_Brok00", "BRA_HengeDisruption", "Brok")
end
function SpawnBaldur()
  local baldur = ND.FindBaldur()
  if baldur ~= nil then
    baldur:Destroy()
  end
  local jointFace = thisObj:GetWorldJointForward(thisObj:GetJointIndex("Bldr_StartJoint"))
  local jointPos = thisObj:GetWorldJointPosition(thisObj:GetJointIndex("Bldr_StartJoint"))
  return game.AI.Spawn(game.FindLevel("HelR090_AI_HengeDisrupt"), jointPos, jointFace, "CRT_Baldur00", "BRA_HengeDisruption", "Baldur")
end
function HideCineLights()
  cineLights:Hide()
end
function PlayCineLights()
  cineLights:Show()
  cineLights:JumpAnimToFrame(0)
  cineLights:PlayAnimToEnd()
end
function SetupActors()
  kraActor = actor.Actor.New("HENGE DISRUPTION: Kratos Actor", game.Player.FindPlayer)
  sonActor = actor.Actor.New("HENGE DISRUPTION: Son Actor", game.AI.FindSon)
  brokActor = actor.Actor.New("HENGE DISRUPTION: Brok Actor")
  bldrActor = actor.Actor.New("HENGE DISRUPTION: Baldur Actor")
  brokActor:SetSpawnFunction(SpawnBrok)
  bldrActor:SetSpawnFunction(SpawnBaldur)
end
function SetupCineSequence()
  local cineSeq = LD.CreateCineSequence(thisLevel, thisObj, "Henge Disruption Sequence")
  local doorObj = game.FindLevel("Cal120_Airlock"):GetGameObject("SpreadDoor_Caldera_Small")
  local slaveTab = {
    {Actor = sonActor},
    {Actor = brokActor},
    {Actor = bldrActor},
    {
      Obj = GameObjects.hengeDisrupt00_P.Child,
      Anim = "narCalHengeDisruption000CineScene"
    },
    {
      Obj = doorObj,
      Anim = "narCalHengeDisruption000CineScene"
    },
    {
      Obj = GameObjects.RealmTravelDoor_Jotunheim.Child,
      Anim = "narCalHengeDisruption000CineScene1"
    }
  }
  cineSeq:SetPostSkipMusic("SND_MX_CAL_start_master", "SND_MX_SonSick_master", "SND_MX_CAL_snake_belly_master")
  cineSeq:SpawnActorAndWait(brokActor)
  cineSeq:SpawnActorAndWait(bldrActor)
  cineSeq:WaitForLoadCheck("Cal120_Airlock")
  cineSeq:WaitForLoadCheck("Cal130_TempleInt")
  cineSeq:WaitForLoadCheck("HelR090_AI_HengeDisrupt")
  cineSeq:ActorForceApproachAndWait(kraActor, {
    Branch = "BRA_HengeDisruption",
    ReferenceJoint = "HengeDisruption_SynchJoint",
    speed = 6,
    stop = false,
    radius = ND.RunArrivalRadius,
    weapon_state = "bare"
  })
  cineSeq:Do(StopDragonFrenzyRun)
  cineSeq:Do(HideHengeRunSprintCamera)
  cineSeq:Do(game.Cinematics.EnableCinematicMode)
  cineSeq:Do(PlayCineLights)
  cineSeq:ActorSync(kraActor, {
    Slaves = slaveTab,
    Branch = "BRA_HengeDisruption",
    ReferenceJoint = "HengeDisruption_SynchJoint"
  })
  cineSeq:Do(function()
    cineSeq:MarkAbleToSkip()
    cineSeq:MarkManualEndSkip(true)
  end)
  cineSeq:Do(_G.StartHengeBridgeAnim)
  cineSeq:WaitSeconds(0.2)
  cineSeq:WaitUntilActorAnimPastPercentage(kraActor, 0.07)
  cineSeq:Do(HideCal120CineLights)
  cineSeq:WaitUntilActorAnimPastPercentage(kraActor, 0.11)
  cineSeq:Do(StartRoomTransition)
  cineSeq:WaitUntilActorAnimPastFrame(kraActor, 305)
  cineSeq:Do(_G.StartHengeRootBridgeAnim)
  cineSeq:WaitUntilActorAnimPastFrame(kraActor, 410)
  cineSeq:Do(_G.RetractHengeRootBridgeAnim)
  cineSeq:WaitUntilActorAnimPastPercentage(kraActor, 0.55591)
  cineSeq:Do(BifrostInsertAttempt_DisperseLeaves_01)
  cineSeq:WaitUntilActorAnimPastPercentage(kraActor, 0.58234)
  cineSeq:Do(BifrostRemoved_ResumeLeafVortex)
  cineSeq:WaitUntilActorAnimPastFrame(kraActor, 1550)
  cineSeq:Do(_G.BaldurPortalOpen)
  cineSeq:WaitUntilActorAnimPastPercentage(kraActor, 0.82761)
  cineSeq:Do(BifrostInsertAttempt_DisperseLeaves_02)
  cineSeq:Do(StartHelheimTransitionFX)
  if warpFlashStartPercent < warpFogStartPercent then
    cineSeq:WaitUntilActorAnimPastPercentage(kraActor, warpFlashStartPercent)
    cineSeq:Do(PlayWarpFlash)
    cineSeq:WaitUntilActorAnimPastPercentage(kraActor, warpFogStartPercent)
    cineSeq:Do(PlayWarpFog)
  else
    cineSeq:WaitUntilActorAnimPastPercentage(kraActor, warpFogStartPercent)
    cineSeq:Do(PlayWarpFog)
    cineSeq:WaitUntilActorAnimPastPercentage(kraActor, warpFlashStartPercent)
    cineSeq:Do(PlayWarpFlash)
  end
  cineSeq:Do(function()
    cineSeq:SetMaxSkipSpeedup(20)
  end)
  cineSeq:WaitForActorFinishMove(kraActor, "MOV_HengeDisruption")
  cineSeq:Do(function()
    game.Compass.SetDesignerForcedHide(true)
  end)
  cineSeq:Do(game.Cinematics.DisableCinematicMode)
  cineSeq:Do(_G.EndHengeBridgeAnim)
  cineSeq:StopPuppetingActor(brokActor)
  cineSeq:StopPuppetingActor(bldrActor)
  cineSeq:DespawnActor(brokActor)
  cineSeq:DespawnActor(bldrActor)
  cineSeq:Do(FinishRoomCleanup)
  cineSeq:Do(_G.BaldurWarpToHel2)
  cineSeq:WaitForLoadCheck("HelR090_Flyover")
  cineSeq:SetCompletedCineNumber(490)
  cineSeq:Do(function()
    LD.SetEntityVariable("CAL_OnDragonRide", false)
  end)
  cineSeq:WaitForActorPlayingMove(kraActor, "MOV_BaldurSkyEnter")
  cineSeq:WaitUntilActorAnimPastPercentage(kraActor, 0.034)
  cineSeq:Do(HideCineLights)
  cineSeq:Do(function()
    game.FindLevel("HelR090_Flyover"):CallScript("SetSkipping", cineSeq.skipping)
  end)
  cineSeq:StartSequence()
end
function CanSeqFire()
  local player = game.Player:FindPlayer()
  return game.Level.GetVariable("CompletedCineNumber") < 490 and player:IsPlayingMove("MOV_BaldurSkyEnter") == false and player:IsPlayingMove("MOV_BaldurSkyExit") == false and game.Level.GetVariable("CompletedCineNumber") >= 470
end
function StopDragonFrenzyRun()
  local peak800 = game.FindLevel("Peak800_DragonRide")
  if peak800 ~= nil then
    peak800:CallScript("StopFrenzyRun")
  end
end
function HideHengeRunSprintCamera()
  local cal100 = game.FindLevel("Cal100_Hub")
  if cal100 ~= nil then
    cal100:CallScript("HideHengeDisruptionSprintCamera")
  end
end
function HideCal120CineLights()
  game.FindLevel("Cal120_Airlock"):CallScript("HideHengeDisruptionLights")
end
function StartRoomTransition()
  GameObjects.realmControllerFXSequencing.LuaObjectScript.SetRoomState_HengeDisruptStart()
end
function BifrostInsertAttempt_DisperseLeaves_01()
  GameObjects.realmControllerFXSequencing.LuaObjectScript.StopVortexLeaves()
  GameObjects.templeReveal:FindSingleGOByName("miniModel"):PlayAnimToFrame(LD.GetRealmFrame("Helheim"), 1.5)
end
function BifrostInsertAttempt_DisperseLeaves_02()
  GameObjects.realmControllerFXSequencing.LuaObjectScript.StopVortexLeaves()
  GameObjects.realm_controller_object.LuaObjectScript.AnimateTempleFall()
end
function BifrostRemoved_ResumeLeafVortex()
  GameObjects.realmControllerFXSequencing.LuaObjectScript.StartVortexLeaves()
end
function StartHelheimTransitionFX()
  GameObjects.realmControllerFXSequencing.LuaObjectScript.SetRoomState_HengeDisruptFXTransition_Helheim()
end
function PlayWarpFlash()
  game.FX.SubmitEffect(warpFlashParams)
end
function PlayWarpFog()
  game.FX.SubmitEffect(warpFogParams)
end
function FinishRoomCleanup()
  GameObjects.realm_controller_object.LuaObjectScript.EnableTable()
  GameObjects.hengeDisrupt00_P.Child:StartAnim("envRealmTravelPlatformRotate360")
  GameObjects.realm_controller_object.LuaObjectScript.SetBridgeAlignmentImmediate("Helheim")
  GameObjects.RealmTravelDoor_Helheim.LuaObjectScript.CloseDoorAndEnable(true, true)
  GameObjects.RealmTravelDoor_Helheim.LuaObjectScript.ForceAutoClose()
  GameObjects.realmControllerFXSequencing.LuaObjectScript.StartBranchAnim_TravelComplete("Helheim")
end
function GetAnimationRate(newFrame)
  local rate = 3
  local maxFrame = 2880
  local halfMax = maxFrame / 2
  local diff = newFrame - startFrame
  if diff < 0 and diff > -halfMax or 0 < diff and 1440 < diff then
    rate = -1 * rate
  end
  return rate
end
