local LD = require("design.LevelDesignLibrary")
local thisObj, thisLevel, language, languageResource, languageGated, discsToComplete, xpReward, journalUpdateID, regionSummaryQuest, Event_OnFailure, Event_OnPartialFailure, Event_OnSuccessfulStart, interactObj, mapSummaryComplete
local enableDelay = 5
function OnScriptLoaded(level, obj)
  thisObj = obj
  thisLevel = level
  languageGated = thisObj:FindLuaTableAttribute("LanguageGated")
  language = thisObj:FindLuaTableAttribute("LanguageToCheck")
  languageResource = language .. "CipherPiece"
  xpReward = thisObj:FindLuaTableAttribute("XpReward")
  journalUpdateID = thisObj:FindLuaTableAttribute("journalUpdateID")
  regionSummaryQuest = thisObj:FindLuaTableAttribute("regionSummaryQuest")
  Event_OnFailure = thisObj:FindLuaTableAttribute("Event_OnFailure")
  if Event_OnFailure then
    Event_OnFailure = LD.ExtractCallbacksForEvent(thisLevel, thisObj, Event_OnFailure)
  end
  Event_OnPartialFailure = thisObj:FindLuaTableAttribute("Event_OnPartialFailure")
  if Event_OnPartialFailure then
    Event_OnPartialFailure = LD.ExtractCallbacksForEvent(thisLevel, thisObj, Event_OnPartialFailure)
  end
  Event_OnSuccessfulStart = thisObj:FindLuaTableAttribute("Event_OnSuccessfulStart")
  if Event_OnSuccessfulStart then
    Event_OnSuccessfulStart = LD.ExtractCallbacksForEvent(thisLevel, thisObj, Event_OnSuccessfulStart)
  end
  if languageGated == true then
    discsToComplete = 4
  end
  interactObj = thisObj:FindSingleGOByName("GenericSonInteract")
  interactObj.LuaObjectScript.GetInteractZone():SetRequiresCriticalBanterComplete(true)
  game.SubObject.Sleep(obj)
  game.SubObject.SetForgetOnCheckpoint(obj)
end
function OnPreStart(level, obj)
  local oldOnInteractCompleteCallbacks = interactObj.LuaObjectScript.TriggerOnInteractCompleteCallbacks
  function interactObj.LuaObjectScript.TriggerOnInteractCompleteCallbacks()
    oldOnInteractCompleteCallbacks()
    UpdateJournal()
  end
  local oldOnEngagedCallbacks = interactObj.LuaObjectScript.TriggerOnInteractEngagedCallbacks
  function interactObj.LuaObjectScript.TriggerOnInteractEngagedCallbacks()
    print("!!!!! Triggering OnEngaged Callbacks")
    oldOnEngagedCallbacks()
    InterruptIfLanguageUnknown()
  end
  SoundOnPreStart()
end
function GetInteractZone()
  return interactObj.LuaObjectScript.GetInteractZone()
end
function InterruptIfLanguageUnknown()
  print("!!!!! Triggering InterruptIfLanguageUnknown")
  if languageGated then
    local discsCollected = game.Wallets.GetResourceValue("HERO", languageResource)
    local banterLine = ""
    if language == "Muspelheim" then
      banterLine = "RuneMarker_03_Fail"
    end
    if language == "Niflheim" then
      banterLine = "RuneMarker_04_Fail"
    end
    if discsCollected == -1 then
      interactObj.LuaObjectScript.Disable()
      if thisObj:FindLuaTableAttribute("IsTowerBrazier") == true then
        CheckForFailureType()
      elseif FreyaCheck() then
        if language == "Niflheim" then
          game.Audio.PlayBanter("Brazier_Indecipherable_Freya_Nif", FailInteract)
        else
          game.Audio.PlayBanter("Brazier_Indecipherable_Freya_Musp", FailInteract)
        end
      else
        game.Audio.PlayBanter(banterLine, FailInteract)
      end
      return
    end
    if 0 < discsCollected and discsCollected < discsToComplete then
      interactObj.LuaObjectScript.Disable()
      if thisObj:FindLuaTableAttribute("IsTowerBrazier") == true then
        CheckForFailureType()
      elseif FreyaCheck() then
        if language == "Niflheim" then
          game.Audio.PlayBanter("Brazier_Indecipherable_Freya_Nif", PartiallyFailInteract)
        else
          game.Audio.PlayBanter("Brazier_Indecipherable_Freya_Musp", PartiallyFailInteract)
        end
      else
        game.Audio.PlayBanter(banterLine, PartiallyFailInteract)
      end
      return
    end
  end
  if thisObj:FindLuaTableAttribute("IsTowerBrazier") then
    local _, progress = game.QuestManager.GetQuestProgressAndGoal("Quest_Labor_LightBrazier")
    if progress == 0 then
      game.Audio.PlayBanter("Brazier_Light_First", thisObj.Parent.Parent.LuaObjectScript.RealmSpecificBanter)
    elseif 0 < progress and progress < 7 then
      game.Audio.PlayBanter("Brazier_Subsequent_Intro", thisObj.Parent.Parent.LuaObjectScript.RealmSpecificBanter)
    elseif progress == 7 then
      game.Audio.PlayBanter("Brazier_Light_Final", thisObj.Parent.Parent.LuaObjectScript.RealmSpecificBanter)
    end
  elseif Event_OnSuccessfulStart then
    LD.ExecuteCallbacksForEvent(thisLevel, thisObj, Event_OnSuccessfulStart)
  end
end
function FreyaCheck()
  if game.Level.GetVariable("FreyaLTWStage") > 0 and game.Level.GetVariable("FreyaLTWStage") < 500 then
    return true
  else
    return false
  end
end
function CheckForFailureType()
  local cineNumber = game.Level.GetVariable("CompletedCineNumber")
  local lo9Quest = game.QuestManager.GetQuestState("Quest_UnfinishedBusiness05_Parent")
  local muspCipherQuest = game.QuestManager.GetQuestState("Quest_SonLanguage_Muspelheim")
  local nifCipherQuest = game.QuestManager.GetQuestState("Quest_SonLanguage_Niflheim")
  local firstMimirRead = game.Level.GetVariable("MimirBrazierRead")
  local lo9InProgressRead = game.Level.GetVariable("BrazierInProgressRead")
  if firstMimirRead == false and 330 <= cineNumber then
    game.Audio.PlayBanter("Brazier_Mimir_Indecipherable", PartiallyFailInteract)
    game.Level.SetVariable("MimirBrazierRead", true)
  elseif lo9Quest ~= "Inactive" and lo9InProgressRead == false then
    game.Audio.PlayBanter("Brazier_Indecipherable_OneLit", PartiallyFailInteract)
    game.Level.SetVariable("BrazierInProgressRead", true)
  elseif muspCipherQuest == "Inactive" and nifCipherQuest == "Inactive" then
    game.Audio.PlayBanter("Brazier_Indecipherable_None", FailInteract)
  elseif muspCipherQuest ~= "Inactive" or nifCipherQuest ~= "Inactive" then
    if nifCipherQuest == "Inactive" or muspCipherQuest == "Inactive" then
      if language == "Muspelheim" and nifCipherQuest == "Complete" then
        game.Audio.PlayBanter("Brazier_Indecipherable_OneDiscComplete", PartiallyFailInteract)
      elseif language == "Niflheim" and muspCipherQuest == "Complete" then
        game.Audio.PlayBanter("Brazier_Indecipherable_OneDiscComplete", PartiallyFailInteract)
      else
        game.Audio.PlayBanter("Brazier_Indecipherable_OneDiscPartial", PartiallyFailInteract)
      end
    else
      game.Audio.PlayBanter("Brazier_Indecipherable_SomeOfBoth", PartiallyFailInteract)
    end
  end
end
function FailInteract()
  print("Fail callback hit")
  EnableAfterDelay()
  if Event_OnFailure then
    LD.ExecuteCallbacksForEvent(thisLevel, thisObj, Event_OnFailure)
  end
end
function PartiallyFailInteract()
  print("Partial fail callback hit")
  EnableAfterDelay()
  if Event_OnPartialFailure then
    LD.ExecuteCallbacksForEvent(thisLevel, thisObj, Event_OnPartialFailure)
  end
end
function UpdateJournal()
  if journalUpdateID ~= nil and journalUpdateID ~= "" then
    journalUpdateID = string.gsub(journalUpdateID, "%s+", "")
    if game.Resources.HasFlag(journalUpdateID, "LoreMarker") then
      LD.UpdateJournal(journalUpdateID, 1)
    else
      LD.UpdateJournal(journalUpdateID, 2)
    end
  end
  if not mapSummaryComplete then
    if regionSummaryQuest ~= nil and regionSummaryQuest ~= "" then
      regionSummaryQuest = string.gsub(regionSummaryQuest, "%s+", "")
      LD.ActivateAndIncrementQuest(regionSummaryQuest)
    end
    mapSummaryComplete = true
    _G.StartLevelTimer(1.35, GiveXP)
  end
  SoftSave()
end
function GiveXP()
  game.Loot.GrantAward(xpReward, "HERO")
end
function InteractAbort()
  interactObj.LuaObjectScript.InteractAbort()
end
function SoftSave()
  game.SubObject.SoftSave(thisObj)
end
function EnableAfterDelay()
  LD.CallFunctionAfterDelay(interactObj.LuaObjectScript.Enable, enableDelay)
end
function Disable()
  interactObj.LuaObjectScript.Disable()
end
function Enable()
  interactObj.LuaObjectScript.Enable()
end
function OnSaveCheckpoint(level, obj)
  return {mapSummaryComplete = mapSummaryComplete}
end
function OnRestoreCheckpoint(level, obj, tab)
  mapSummaryComplete = tab.mapSummaryComplete
end
local wallRuneReadOverride = {
  SoundEmitter = nil,
  SNDFXLP = "SND_MAG_Rune_Read_Burn_Away_LP",
  StartFrame = 35,
  EndFrame = 178
}
local loreMarkerOverride = {
  SoundEmitter = nil,
  SNDFXLP = "SND_MAG_Rune_Read_Burn_Away_LP",
  StartFrame = 45,
  EndFrame = 178
}
function SoundOnPreStart()
  SoundSetup(wallRuneReadOverride)
end
function WallRuneReadSoundSetup(newEmitter)
  if newEmitter ~= nil then
    wallRuneReadOverride.SoundEmitter = newEmitter
    thisObj:FindSingleGOByName("GenericSonInteract").Child:HideAudio()
  end
  SoundSetup(wallRuneReadOverride)
end
function LoreMarkerRuneReadSoundSetup(newEmitter)
  if newEmitter ~= nil then
    loreMarkerOverride.SoundEmitter = newEmitter
    thisObj:FindSingleGOByName("GenericSonInteract").Child:HideAudio()
  end
  SoundSetup(loreMarkerOverride)
end
function SoundSetup(newSoundTable)
  if newSoundTable ~= nil then
    interactObj.LuaObjectScript.SoundSetup(newSoundTable)
  end
end
