94 lines
2.7 KiB
C#
94 lines
2.7 KiB
C#
using System;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using CsvHelper.Configuration;
|
|
using CsvHelper;
|
|
using System.Globalization;
|
|
using Splat;
|
|
using StarsAssistant.Services;
|
|
|
|
namespace StarsAssistant.CSV;
|
|
|
|
public class PlanetLoader
|
|
{
|
|
/// <summary>
|
|
/// Reference to the game metadata, retrieved by DI
|
|
/// </summary>
|
|
protected Services.Game Game = Locator.Current.GetService<Services.Game>()!;
|
|
|
|
/// <summary>
|
|
/// CSV Configuration to use for importing Planet files.
|
|
/// </summary>
|
|
protected CsvConfiguration CsvConfig;
|
|
|
|
/// <summary>
|
|
/// Construction
|
|
/// </summary>
|
|
public PlanetLoader()
|
|
{
|
|
CreateConfig();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates the CSV configuration for planets.
|
|
/// </summary>
|
|
[MemberNotNull(nameof(CsvConfig))]
|
|
protected void CreateConfig()
|
|
{
|
|
CsvConfig = CsvConfiguration.FromAttributes<Planet>(CultureInfo.InvariantCulture);
|
|
CsvConfig.Delimiter = "\t";
|
|
CsvConfig.Escape = '\0';
|
|
CsvConfig.MissingFieldFound = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Import the planet file for the given Race.
|
|
/// </summary>
|
|
/// <param name="race">Import File</param>
|
|
public void ImportForRace(Model.Race race)
|
|
{
|
|
using var db = Locator.Current.GetService<Model.StarsDatabase>()!;
|
|
using var reader = new StreamReader(Game.PlanetFileForRace(race), System.Text.Encoding.Latin1);
|
|
using var csv = new CsvReader(reader, CsvConfig);
|
|
|
|
List<CSV.Planet> records = csv.GetRecords<Planet>().ToList();
|
|
var planetByPlayer = from csvp in records
|
|
group csvp by csvp.Owner into byOwners
|
|
select byOwners;
|
|
|
|
foreach (var owner in planetByPlayer)
|
|
{
|
|
Model.Race? r;
|
|
if (owner.Key == race.Name)
|
|
{
|
|
r = race;
|
|
}
|
|
else
|
|
{
|
|
r = db.Race.Find(owner.Key);
|
|
if (r == null)
|
|
{
|
|
r = new() { Name = owner.Key };
|
|
db.Add(r);
|
|
}
|
|
}
|
|
|
|
foreach (Planet csvp in owner)
|
|
{
|
|
Model.Planet? p = db.Planet.Find(csvp.Name);
|
|
if (p == null)
|
|
{
|
|
p = new() { Name = csvp.Name };
|
|
csvp.UpdateDbPlanet(p);
|
|
db.Add(p);
|
|
}
|
|
else
|
|
{
|
|
csvp.UpdateDbPlanet(p);
|
|
db.Update(p);
|
|
}
|
|
}
|
|
db.SaveChanges();
|
|
}
|
|
}
|
|
}
|