local LD = require("design.LevelDesignLibrary")
local thisObj, player, leadingCharacter, pathName, path, startEnabled
local enabled = false
function OnScriptLoaded(level, obj)
  thisObj = obj
  player = game.Player.FindPlayer()
  leadingCharacter = obj:GetLuaTableAttribute("leadingCharacter")
  pathName = thisObj:GetLuaTableAttribute("pathName")
  if pathName == nil or pathName == "" then
    engine.Warning("Please enter the name of a nav curve in the 'pathName' Lua Toolbox attribute for object '" .. thisObj:GetName() .. "'")
  end
  path = level:FindSingleNavCurve(pathName)
  if path == nil then
    engine.Warning("Couldn't find nav curve '" .. pathName .. "' in level '" .. level.Name .. "'.  Please enter the name of an existing nav curve in the 'pathName' Lua Toolbox attribute for object '" .. thisObj:GetName() .. "'")
  end
  local warningMessage = "FOUND DEPRECATED SPEED CONTROL ZONES: "
  local speedControlZones = game.World.FindGameObjectsByMarker("SpeedControlZone")
  for _, z in ipairs(speedControlZones) do
    warningMessage = warningMessage .. z:GetName() .. ", "
  end
  if 0 < #speedControlZones then
    warningMessage = warningMessage .. [[

Please remove the 'Hash('SpeedControlZone')' entity marker from these zones,
Each zone object should contain a SpeedControlZone refnode
(GameplayModules/Narrative/_SceneTools/Component_SpeedControlZone.mb)
]]
    engine.Warning(warningMessage)
  end
  startEnabled = thisObj:GetLuaTableAttribute("startEnabled")
  game.SubObject.Sleep(thisObj)
end
function OnStart(level, obj)
  if startEnabled then
    Enable()
  end
end
function OnSaveCheckpoint(level, obj)
  return {enabled = enabled}
end
function OnRestoreCheckpoint(level, obj, savedInfo)
  startEnabled = savedInfo.enabled
end
function OnUpdate(level, obj)
  if leadingCharacter == nil then
    Disable()
  end
end
function Enable()
  if not enabled then
    if leadingCharacter == "Son" then
      leadingCharacter = game.AI.FindSon()
    elseif leadingCharacter == "Freya" then
      leadingCharacter = LD.FindFreya()
    end
    if leadingCharacter ~= nil then
      enabled = true
      game.SubObject.Wake(thisObj)
      player:CallScript("SpeedControl_AddSpline", thisObj, {path = path, leadingCharacter = leadingCharacter})
    elseif leadingCharacter == "Freya" then
      engine.Error("YouShallNotPass module is configured to keep Kratos behind Freya, but she doesn't exist.\n" .. LD.GetParentTrace(thisObj))
    end
  end
end
function Disable()
  if enabled then
    enabled = false
    game.SubObject.Sleep(thisObj)
    player:CallScript("SpeedControl_RemoveSpline", thisObj)
  end
end
