asset.require("spice/base")

local createGlobeWithoutName = function(identifier, parent, parentSpiceName, spiceName,
    radii, tags, trailTags, guiPath, trailColor, orbitPeriod, kernels)
  return {
      Identifier = identifier,
      Parent = parent,
      Transform = {
        Translation = {
          Type = "SpiceTranslation",
          Target = spiceName,
          Observer = parentSpiceName,
          Kernels = kernels
        }
      },
      Renderable = {
        Type = "RenderableGlobe",
        Radii = radii,
        SegmentsPerPatch = 64,
        Layers = {},
        Tag = tags
      },
      GUI = {
        Path = guiPath
      }
  },
  {
    Identifier = identifier .. "Trail",
    Parent = parent,
    Renderable = {
      Type = "RenderableTrailOrbit",
      Translation = {
        Type = "SpiceTranslation",
        Target = spiceName,
        Observer = parentSpiceName
      },
      Color = trailColor,
      Period = orbitPeriod,
      Resolution = 1000,
      Tag = trailTags,
    },
    GUI = {
      Path = guiPath
    }
  }
end

local createGlobeWithName = function(identifier, name, parent, parentSpiceName, spiceName,
    radii, tags, trailTags, guiPath, trailColor, orbitPeriod, kernels, layers)
  g, t = createGlobeWithoutName(identifier, parent, parentSpiceName, spiceName, radii,
    tags, trailTags, guiPath, trailColor, orbitPeriod, kernels, layers)
  g.GUI.Name = name
  t.GUI.Name = name .. " Trail"

  return g, t
end
asset.export("createGlobeWithoutName", createGlobeWithoutName)
asset.export("createGlobeWithName", createGlobeWithName)


local createGlobes = function(t)
  for _,v in pairs(t) do
    if type(v) ~= "table" then
      local warning = "The table passed to 'createGlobes' was not a table of tables"
      openspace.printWarning(warning)
      -- We return an empty table of tables to silence a potential future warning
      return {{}}
    end
  end

  local result = {}

  for i, v in ipairs(t) do
    local globe = nil
    local trail = nil
    if not v.Layers then
      v.Layers = {}
    end
    if not v.TrailTags then
      v.TrailTags = {}
    end
    if v.Name then
      globe, trail = createGlobeWithName(
        v.Identifier,
        v.GUI.Name,
        v.Parent.Identifier,
        v.Parent.Spice,
        v.Spice,
        v.Radii,
        v.Tags,
        v.TrailTags,
        v.GUI.Path,
        v.TrailColor,
        v.OrbitPeriod,
        v.Kernels,
        v.Layers
      )
    else
      globe, trail = createGlobeWithoutName(
        v.Identifier,
        v.Parent.Identifier,
        v.Parent.Spice,
        v.Spice,
        v.Radii,
        v.Tags,
        v.TrailTags,
        v.GUI.Path,
        v.TrailColor,
        v.OrbitPeriod,
        v.Kernels,
        v.Layers
      )
    end

    table.insert(result, globe)
    table.insert(result, trail)
  end
  return result
end
asset.export("createGlobes", createGlobes)
