local LD = require("design.LevelDesignLibrary")
local uiCalls = require("ui.uicalls")
local player, thisLevel, doorHel, alfChkptZone, helChkptZone
local bAmuletCollected = false
function OnScriptLoaded(level)
  player = game.Player.FindPlayer()
  thisLevel = level
  doorHel = GameObjects.RealmTravelDoor_Helheim
  alfChkptZone = GameObjects.CheckpointBackFromAlfheim
  helChkptZone = GameObjects.CheckpointBackFromHelheim
end
function OnFirstStart(level, obj)
  GameObjects.HelheimRPortal:Hide()
  GameObjects.Helheim_Return1:HideEntityVolume()
  GameObjects.Helheim_Return2:HideEntityVolume()
  alfChkptZone:HideEntityVolume()
  helChkptZone:HideEntityVolume()
  GameObjects.Helheim_Realm_Travel_Room:ShowEntityVolume()
  GameObjects.WhiteRunestone_Upright:Hide()
  AttenuateLowerLensFlare()
end
function OnStart(level)
  LD.RegisterForCineUpdate(level, {
    {
      at = 250,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    },
    {
      at = 310,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    },
    {
      at = 330,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    },
    {
      at = 360,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    },
    {
      at = 380,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    },
    {
      at = 387,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    },
    {
      at = 400,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    },
    {
      at = 470,
      immediateFn = function()
        GameObjects.Helheim_Return1:ShowEntityVolume()
        GameObjects.HelheimRPortal:Show()
        LD.SetEntityVariable("CAL_OnDragonRide", false)
      end,
      fn = function()
        GameObjects.Helheim_Return1:ShowEntityVolume()
        GameObjects.HelheimRPortal:Show()
        LD.SetEntityVariable("CAL_OnDragonRide", false)
      end
    },
    {
      at = 500,
      immediateFn = function()
        GameObjects.AreaAnnounce130:Show()
      end,
      fn = function()
        GameObjects.AreaAnnounce130:Show()
      end
    }
  })
  LD.RegisterForVariableUpdate(level, "BridgePosition", {
    immediateFn = function()
      GameObjects.realm_controller_object.LuaObjectScript.SetBridgeAlignmentImmediate()
    end,
    fn = function()
      GameObjects.realm_controller_object.LuaObjectScript.SetBridgeAlignment()
    end
  })
  LD.RegisterForVariableUpdate(level, "CurrentRealm", {
    immediateFn = function()
      SetCurrentRealm()
    end,
    fn = function()
      SetCurrentRealm()
    end
  })
  if LD.GetEntityVariable("CAL_TempleFlipped") then
    GameObjects.WhiteRunestone_UpsideDown:Hide()
    TurnOffLowerLensFlare()
    GameObjects.DispelSphere_UpsideDown.LuaObjectScript.Disable()
    if not bAmuletCollected then
      GameObjects.DispelSphere_Upright.LuaObjectScript.Enable()
      GameObjects.WhiteRunestone_Upright:Show()
      CycleUpperLensFlare()
      GameObjects.Mask_upright.Child:StartAnim("maskLoopFloating")
      GameObjects.Mask_upright.Child:PlayAnimCycle()
    else
      GameObjects.DispelSphere_Upright.LuaObjectScript.Disable()
      GameObjects.WhiteRunestone_Upright:Hide()
      TurnOffUpperLensFlare()
    end
  else
    GameObjects.WhiteRunestone_Upright:Hide()
    GameObjects.WhiteRunestone_UpsideDown:Show()
    AttenuateLowerLensFlare()
    TurnOffUpperLensFlare()
    GameObjects.Mask_upsideDown.Child:StartAnim("maskLoopFloating")
    GameObjects.Mask_upsideDown.Child:PlayAnimCycle()
    GameObjects.DispelSphere_Upright.LuaObjectScript.Disable()
    GameObjects.DispelSphere_UpsideDown.LuaObjectScript.Enable()
  end
  if LD.GetEntityVariable("CAL_TempleFlipped") then
    GameObjects.flip_hide:Hide()
    GameObjects.flip_vis:Show()
  else
    GameObjects.flip_hide:Show()
    GameObjects.flip_vis:Hide()
  end
  if game.Level.GetVariable("CompletedCineNumber") >= 610 and LD.GetCurrentRealm() == "Midgard" then
    UnlockMidgardDoor()
  end
end
function CycleLowerLensFlare()
  GameObjects.LowerTalisman_flare.Child:ClearAllAnimationCallbacks()
  GameObjects.LowerTalisman_flare.Child:JumpAnimationToPercent(0)
  GameObjects.LowerTalisman_flare.Child:PlayAnimationToFrame(172)
  GameObjects.LowerTalisman_flare.Child:OnAnimationDone(thisLevel, "CycleLowerLensFlare")
end
function TurnOffLowerLensFlare()
  GameObjects.LowerTalisman_flare.Child:ClearAllAnimationCallbacks()
  GameObjects.LowerTalisman_flare.Child:JumpAnimationToFrame(172)
  GameObjects.LowerTalisman_flare.Child:PlayAnimationToEnd()
end
function CycleUpperLensFlare()
  GameObjects.UpperTalisman_flare.Child:ClearAllAnimationCallbacks()
  GameObjects.UpperTalisman_flare.Child:JumpAnimationToPercent(0)
  GameObjects.UpperTalisman_flare.Child:PlayAnimationToFrame(172)
  GameObjects.UpperTalisman_flare.Child:OnAnimationDone(thisLevel, "CycleLowerLensFlare")
  GameObjects.UpperTalisman_light:Show()
end
function TurnOffUpperLensFlare()
  GameObjects.UpperTalisman_flare.Child:ClearAllAnimationCallbacks()
  GameObjects.UpperTalisman_flare.Child:JumpAnimationToFrame(172)
  GameObjects.UpperTalisman_flare.Child:PlayAnimationToEnd()
  GameObjects.UpperTalisman_light:Hide()
end
function AttenuateLowerLensFlare()
  GameObjects.LowerTalisman_flare.Child:ClearAllAnimationCallbacks()
  GameObjects.LowerTalisman_flare.Child:JumpAnimationToFrame(198)
  GameObjects.LowerTalisman_flare.Child:PauseAnimation()
end
function OnUpdate(level)
  LD.DisplayEntityDebug(level, 12)
end
function SetCurrentRealm()
  local currentRealm = LD.GetCurrentRealm()
  local realmNames = LD.GetRealmInfo().names
  if currentRealm == "Midgard" then
    for _, realm in pairs(realmNames) do
      GameObjects["RealmTravelDoor_" .. realm]:FindSingleGOByName("VanaheimDoorR1"):Show()
      GameObjects["RealmTravelDoor_" .. realm]:FindSingleGOByName("VanaheimDoorL1"):Show()
    end
  else
    for _, realm in pairs(realmNames) do
      GameObjects["RealmTravelDoor_" .. realm]:FindSingleGOByName("VanaheimDoorR1"):Hide()
      GameObjects["RealmTravelDoor_" .. realm]:FindSingleGOByName("VanaheimDoorL1"):Hide()
    end
  end
end
function OpenRealmTravelDoorToAlfheim()
  if game.Level.GetVariable("FreyaLTWStage") == 80 and game.Level.GetVariable("CompletedCineNumber") == 205 then
    local doorObj = GameObjects.RealmTravelDoor_Alfheim.Child
    local player = game.Player.FindPlayer()
    local branchName = "BRA_DoorSpreadOpen_RealmTravelFreya"
    local freyaRef = LD:FindFreya()
    doorObj.LuaObjectScript.EnableCinematicTrigger(true)
    player:RequestInteract(doorObj)
    LD.PlayApproach_GroupSync(doorObj, {
      {player, branchName},
      {
        game.AI.FindSon(),
        branchName
      },
      {freyaRef, branchName}
    }, "DoorSpreadRealmFreyaOpen", true, "synchJointFront")
    FreyaLTW_ExitRealmTravelRoom()
    local modifyMotionSeq = LD.CreateCineSequence(thisLevel, doorObj, "RealmDoor to AirlockDoor ModifyCreatureMotion")
    modifyMotionSeq:WaitForFunctionTrue(function()
      return not freyaRef:IsInNavigationMove()
    end)
    modifyMotionSeq:WaitForFunctionTrue(function()
      return freyaRef:IsInNavigationMove()
    end)
    modifyMotionSeq:Do(function()
      freyaRef:ModifyCreatureMotion({MovementPriority = 1000, UnmovableByCreature = true})
    end)
    modifyMotionSeq:StartSequence()
  end
end
function FreyaLTW_ExitRealmTravelRoom()
  local freyaLTW = game.FindLevel("FreyaLTW")
  if freyaLTW ~= nil then
    freyaLTW:CallScript("LTW_EnterAirlock_ToAlfheim")
  end
end
function OnEvaluateLoadGroup_LoadGroup_AI()
  local currentRealm = LD.GetCurrentRealm()
  local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
  if currentRealm == "Midgard" then
    if 190 <= completedCineNumber and completedCineNumber < 210 then
      return "AI_Visit_04"
    elseif 250 <= completedCineNumber and completedCineNumber < 263 then
      return "AI_Visit_01"
    elseif completedCineNumber == 380 then
      return "AI_Visit_02"
    elseif completedCineNumber == 500 then
      return "AI_Visit_03"
    else
      return nil
    end
  elseif currentRealm == "Muspelheim" then
    if 250 <= completedCineNumber and completedCineNumber < 263 then
      return "AI_Visit_01"
    end
  elseif 190 <= completedCineNumber and completedCineNumber < 210 then
    return "AI_Visit_04"
  end
end
function SpeedControl_RT_Platform_Enter()
  local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
  if 210 <= completedCineNumber then
    player:SetMaxSpeedOverride(4)
  end
end
function SpeedControl_RT_Platform_Exit()
  local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
  if 210 <= completedCineNumber then
    player:ClearMaxSpeedOverride()
  end
end
function OnEvaluateLoadGroup_RealmTravel()
  return GameObjects.realm_controller_object.LuaObjectScript.OnEvaluateLoadGroup_RealmTravel()
end
function RestoreTreeEnergy()
  GameObjects.realmControllerFXSequencing.LuaObjectScript.RestoreTreeEnergy()
end
function Helheim_Objective020()
  LD.CompleteQuest("Quest_Helheim_Objective020")
end
function StartHengeBridgeAnim()
  game.FindLevel("Cal120_Airlock"):CallScript("StartHengeBridgeAnim")
  GameObjects.HengeDisruptGroup:JumpAnimToFrame(1)
  GameObjects.HengeDisruptGroup:PauseAnim()
  GameObjects.realm_controller_object.LuaObjectScript.ResetPressurePlatesAndRootBridgeToRealmDirection("Jotunheim")
end
function StartHengeRootBridgeAnim()
  GameObjects.worldTreeBridge00_P.LuaObjectScript.Extend(2)
end
function RetractHengeRootBridgeAnim()
  GameObjects.worldTreeBridge00_P.LuaObjectScript.Retract()
end
function EndHengeBridgeAnim()
  local cal120 = game.FindLevel("Cal120_Airlock")
  if cal120 ~= nil then
    cal120:CallScript("SetBridgeAlignmentImmediate", "Helheim")
  end
end
function BaldurWarpToHel2()
  GameObjects.Helheim_Return1:HideEntityVolume()
  GameObjects.Helheim_Return2:ShowEntityVolume()
  game.UI.LoadCheck("HelR090_Flyover")
  LD.SetSelectedRealm("Helheim")
  LD.SetCurrentRealm("Helheim")
  LD.SetBridgePosition("Helheim")
  GameObjects.RealmTravelDoor_Jotunheim.Child:StartAnim("DoorSpreadStayOpen")
  GameObjects.RealmTravelDoor_Jotunheim.Child:PauseAnim()
  GameObjects.HengeDisruptGroup:JumpAnimToFrame(0)
  GameObjects.HengeDisruptGroup:PauseAnim()
end
function BaldurPortalOpen()
  doorHel.LuaObjectScript.ForceAutoOpen(4)
  GameObjects.RealmTravelDoor_Jotunheim.LuaObjectScript.ForceAutoClose(4)
  print("opening door for portal")
end
function BookmarkWarpToHel2()
  print("bookmark is warping player to Hel2")
  LD.SetEntityVariable("CAL_OnDragonRide", false)
  GameObjects.Helheim_Return1:HideEntityVolume()
  GameObjects.Helheim_Return2:ShowEntityVolume()
  LD.CallFunctionAfterDelay(function()
    player:Warp(engine.Vector.New(40, 10, 50), player:GetWorldForward())
  end, 5)
end
function TurnOnAlfheimChkpt()
  alfChkptZone:ShowEntityVolume()
  print("cal130 turning on the alfheim checkpoint zone")
end
function TurnOnHelheimChkpt()
  helChkptZone:ShowEntityVolume()
  print("cal130 turning on the helheim checkpoint zone")
end
function AreaAnnounce130()
  uiCalls.UI_Event_DiscoverLocation("Realm Travel Room")
  GameObjects.AreaAnnounce130:Hide()
end
function StartQuest_Obj502()
  LD.CompleteQuest("Quest_Foothills_Objective502")
  game.Compass.SetDesignerForcedHide(true)
end
function ShowLowerLights()
  GameObjects.Cal130_LOWER_Level:Show()
end
function HideLowerLights()
  GameObjects.Cal130_LOWER_Level:Hide()
end
function ShutOffSonSpline()
  GameObjects.LTW_RealmTravelIntro_Son.LuaObjectScript.Disable()
end
function EnableDoorCAFromTempleFlip()
  GameObjects.SonEnterFromTempleFlip.LuaObjectScript.Enable()
end
function OpenDoorFromTempleFlip()
  local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
  if 510 <= completedCineNumber and completedCineNumber < 512 and not bAmuletCollected then
    GameObjects.TempleFlipSonSpline.LuaObjectScript.Enable()
    GameObjects.TempleFlipSon_ShieldEyes.LuaObjectScript.Enable()
    GameObjects.LowerTalismanAnim:JumpAnimationToPercent(0)
    GameObjects.floor_mid:JumpAnimationToPercent(1)
    GameObjects.floor_mid:PlayAnimationToFrame(120, {Rate = -1})
    TurnOffLowerLensFlare()
  end
  GameObjects.SonEnterFromTempleFlip.LuaObjectScript.Enable()
end
function ArriveFromTempleFlip()
  LD.CompleteQuest("Quest_Caldera_Objective730")
  local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
  if 510 <= completedCineNumber and completedCineNumber < 515 then
    GameObjects.CenterCollision:HideCollision()
  end
end
function OpenJotunheimDoor()
  GameObjects.RealmTravelDoor_Jotunheim.LuaObjectScript.SnapDoorsToOpenStartFrames()
  GameObjects.RealmTravelDoor_Jotunheim.LuaObjectScript.ForceAutoOpen(2)
end
function CloseJotunheimDoor()
  GameObjects.RealmTravelDoor_Jotunheim.LuaObjectScript.SnapOutterDoorToCloseStartFrame()
  GameObjects.RealmTravelDoor_Jotunheim.LuaObjectScript.ForceAutoClose(-2)
  GameObjects.RealmTravelDoor_Jotunheim.LuaObjectScript.Disable()
end
function LockMidgardDoor()
  GameObjects.RealmTravelDoor_Vanaheim.Child.LuaObjectScript.Lock()
end
function UnlockMidgardDoor()
  GameObjects.RealmTravelDoor_Vanaheim.Child.LuaObjectScript.Unlock()
end
function HideTree()
  GameObjects.HelheimRPortal:Hide()
end
function TakeRuneStone()
  LD.GiveFastTravelStageOne()
  LD.GiveTyrUnlock()
  bAmuletCollected = true
end
function OnJotunheimDoorInteractComplete()
  LD.CompleteQuest("Quest_Caldera_Objective745")
end
function Complete_Quest_Caldera_Objective870()
  LD.CompleteQuest("Quest_Caldera_Objective870")
  game.Compass.SetGatewayMarkerIsOpen("CALT_130_Helper_011x", true)
  game.Compass.SetGatewayMarkerIsOpen("CALT_130_Helper_013", true)
  game.Compass.SetGatewayMarkerIsOpen("CALT_130_Helper_011x1", false)
end
function LoadCheckCal120()
  game.UI.LoadCheck("Cal120_Airlock", "Cal120_AI_BrokShop", "Cal120_AI_BrokCares", "Cal120_AI_BrokSavesCat")
end
function OnSaveCheckpoint(level)
  return {bAmuletCollected = bAmuletCollected}
end
function OnRestoreCheckpoint(level, tab)
  bAmuletCollected = tab.bAmuletCollected
end
function TalismanCheckpoint()
  local bookmarks = require("design.Bookmarks")
  local tableEntry = bookmarks["BOOKMARK_" .. "31_TempleFlip_060_WhiteRunestoneAcquired"]
  game.World.StoreCheckpointAndBookmark(tableEntry)
end
