local LD = require("design.LevelDesignLibrary")
local ND = require("design.NarrativeDesignLibrary")
local actor = require("narrative.actor")
local CCEC = require("camera.camera_cineentercamera")
local timers = require("level.timer")
local uiCalls = require("ui.uicalls")
local thisObj, thisLevel, player, kraActor, sonActor
local playedPOI = false
local mimirHeadProp, cal130, cineEnterCamera_MimirPickup
local GetLAMSMsg = function(lamsID, itemRef)
  local msg = ""
  local messageFound = false
  if lamsID ~= nil then
    local lamsMsg = "[MSG:" .. lamsID .. "]"
    if lamsMsg ~= nil then
      msg = lamsMsg
      messageFound = true
      local showSourceText = engine.VFSGetBool("/UI/Text/Show Source Text") == 1
      if showSourceText then
        msg = tostring(itemRef) .. " " .. msg
      end
    end
  end
  if messageFound == false then
    msg = "LAMS ID " .. tostring(lamsID) .. " Not Found"
  end
  return msg, messageFound
end
function OnScriptLoaded(level, obj)
  thisObj = obj
  thisLevel = level
  player = game.Player.FindPlayer()
  game.SubObject.Sleep(obj)
end
function OnStart(level, obj)
  SetupProps()
  local cineNum = game.Level.GetVariable("CompletedCineNumber")
  if cineNum <= 610 then
    SetupActors()
  end
  if CanPlaySeq() and player:PickupIsAcquired("MimirHead") then
    player:PickupRelinquish("MimirHead")
  end
end
function TryInitializeSeq()
  if CanPlaySeq() then
    StartPropIdles()
  end
end
function UpdateQuest()
  game.QuestManager.ProposeQuestState("Quest_ReturnHome_Objective1", "Complete")
  LD.CallFunctionAfterDelay(TriggerSlashScreens, 1)
end
function TriggerSlashScreens()
  if game.Map.AllRegionSummariesCompleted and not game.Map.AllRegionSummariesCompleted() then
    local showValkyriesMessage = CheckForValkSplash()
    local completionMessageDisplayTime = showValkyriesMessage and 1 or 3.5
    uiCalls.SendSplashScreenDesignerMessage({
      Title = 43080,
      Text = 43081,
      AdvanceType = uiCalls.msgParam.ADVANCE_PRESS,
      DisplayTime = completionMessageDisplayTime,
      MessageVariant = uiCalls.msgParam.SPLASHSCREEN_NO_IMAGE
    })
    if showValkyriesMessage then
      UpdateValkyrieMarkers()
      uiCalls.SendSplashScreenDesignerMessage({
        Title = 43078,
        Text = 43079,
        AdvanceType = uiCalls.msgParam.ADVANCE_PRESS,
        ImageMaterialName = "valkyrie_map",
        FooterButtonInfo = {
          {
            Text = "[AdvanceButton] " .. GetLAMSMsg(588),
            EventHandlers = {
              {
                Events = {
                  "EVT_Advance_Release"
                },
                Handler = nil,
                UICalls = {
                  {
                    CallName = "UI_Event_Open_Map_Menu",
                    ArgTable = {"Midgard"}
                  }
                }
              }
            }
          }
        }
      })
    end
  end
  LD.CallFunctionAfterDelay(ActivateQuest, 2)
  game.SubmitActivityFeedStory("12_GameComplete")
end
function CheckForValkSplash()
  local valkyrieSummaryTable = {
    {
      SummaryQuest = "RegionSummary_Foothills_Valkryie_Parent",
      mapMarker = "FOOT_250_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Riverpass_Valkryie_Parent",
      mapMarker = "RP_975_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_StoneMason_Valkryie_Parent",
      mapMarker = "SM_110_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Alfheim_Valkryie_Parent",
      mapMarker = "ALF_355_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Helheim_Valkryie_Parent",
      mapMarker = "HEL_350_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Peakspass_Valkryie_Parent",
      mapMarker = "PP_205_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Muspelheim_Valkryie_Parent",
      mapMarker = "MSP_100_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Niflheim_Valkryie_Parent",
      mapMarker = "NIF_100_ValkyrieLocation"
    }
  }
  for _, y in ipairs(valkyrieSummaryTable) do
    if y ~= nil and y.SummaryQuest ~= nil then
      local questState = game.QuestManager.GetQuestState(y.SummaryQuest)
      if questState ~= "Complete" then
        return true
      end
    end
  end
  return false
end
function UpdateValkyrieMarkers()
  local valkyrieSummaryTable = {
    {
      SummaryQuest = "RegionSummary_Foothills_Valkryie_Parent",
      mapMarker = "FOOT_250_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Riverpass_Valkryie_Parent",
      mapMarker = "RP_975_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_StoneMason_Valkryie_Parent",
      mapMarker = "SM_110_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Alfheim_Valkryie_Parent",
      mapMarker = "ALF_355_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Helheim_Valkryie_Parent",
      mapMarker = "HEL_350_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Peakspass_Valkryie_Parent",
      mapMarker = "PP_205_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Muspelheim_Valkryie_Parent",
      mapMarker = "MSP_100_ValkyrieLocation"
    },
    {
      SummaryQuest = "RegionSummary_Niflheim_Valkryie_Parent",
      mapMarker = "NIF_100_ValkyrieLocation"
    }
  }
  for _, y in ipairs(valkyrieSummaryTable) do
    if y ~= nil and y.SummaryQuest ~= nil then
      local questState = game.QuestManager.GetQuestState(y.SummaryQuest)
      if questState ~= "Complete" then
        LD.SetMarkerState(y.mapMarker, 1)
      end
    end
  end
end
function ActivateQuest()
  if game.UI.UpdateNewGamePlusAvailable ~= nil then
    game.UI.UpdateNewGamePlusAvailable()
  end
  game.World.StoreCheckpoint()
end
function OnSaveCheckpoint(level, obj)
  return {played = playedPOI}
end
function OnRestoreCheckpoint(level, obj, savedInfo)
  playedPOI = savedInfo.played
end
function SetupActors()
  kraActor = actor.Actor.New("MIMIR PICKUP: Kratos Actor", game.Player.FindPlayer)
  sonActor = actor.Actor.New("MIMIR PICKUP: Son Actor", game.AI.FindSon)
end
function SetupProps()
  mimirHeadProp = GameObjects.mimirHeadProp.Child
  HideProps()
end
function HideProps()
  mimirHeadProp:Hide()
end
function StartPropIdles()
  mimirHeadProp:Show()
  local eye = mimirHeadProp:FindSingleGOByName("mimir00_eyeLeft")
  eye:ShowJoint(0)
  eye:Show()
end
function GetCal130()
  if cal130 == nil then
    cal130 = game.FindLevel("Cal130_TempleInt")
  end
  return cal130
end
function SetupPOISeq()
  if CanPlaySeq() then
    local seq = ND.CreateCineSequence(thisLevel, thisObj, "MimirPickupSequence")
    local slaveTab = {
      {Actor = sonActor}
    }
    seq:RequestCineModeAndWait(kraActor, thisObj)
    seq:Do(StartCineEnter_MimirPickup)
    seq:ActorForceApproachAndWait(kraActor, {
      Branch = "BRA_MimirPickup",
      ReferenceJoint = "MimirPickup_SynchJoint",
      speed = ND.KraWalkSpeed,
      stop = false,
      foot = game.Creature.Foot.kLeft,
      radius = ND.ArrivalRadius,
      weapon_state = "bare",
      strafe_distance = 5.5
    })
    seq:ActorSync(kraActor, {
      Slaves = slaveTab,
      Branch = "BRA_MimirPickup",
      ReferenceJoint = "MimirPickup_SynchJoint"
    })
    seq:WaitForFunctionTrue(function()
      return player:PickupIsAcquired("MimirHead") and player.MimirHead ~= nil
    end)
    seq:Do(function()
      player:CallScript("LuaHook_HideMimirEye")
    end)
    seq:Do(CloseJotunheimRealmDoor)
    seq:WaitForAndCompleteCineMode(kraActor, thisObj)
    seq:StopPuppetingActor(sonActor)
    seq:StopPuppetingActor(kraActor)
    seq:Do(function()
      playedPOI = true
    end)
    seq:Do(function()
      game.Audio.SetBanterFact("played020_MidgardWeatherReport", false)
    end)
    seq:Do(UpdateQuest)
    seq:StartSequence()
  end
end
function LuaHook_HideHeadProp()
  HideProps()
end
function LuaHook_PlayBanter()
  game.Audio.PlayBanter("010_MimirRejoins")
end
function CanPlaySeq()
  return game.Level.GetVariable("CompletedCineNumber") == 610 and not playedPOI
end
function CloseJotunheimRealmDoor()
  local jotDoor = GetCal130():FindSingleGameObject("RealmTravelDoor_Jotunheim")
  jotDoor.Child:CallScript("CallScript_JotunheimReturnCleanup")
  local cal300 = game.FindLevel("Cal300_JotunheimLH")
  if cal300 ~= nil then
    cal300:CallScript("DisableLTW_Down")
  end
end
function OnUpdate()
  if cineEnterCamera_MimirPickup ~= nil then
    cineEnterCamera_MimirPickup:Update()
  end
end
function StartCineEnter_MimirPickup()
  game.SubObject.Wake(thisObj)
  cineEnterCamera_MimirPickup = CCEC.CineEnterCamera.New("ENV_CineEnter_MimirPickup", 7)
  cineEnterCamera_MimirPickup:SetCallback(DestroyCineEnter_MimirPickup)
  cineEnterCamera_MimirPickup:Start()
end
function DestroyCineEnter_MimirPickup()
  cineEnterCamera_MimirPickup = nil
  game.SubObject.Sleep(thisObj)
end
