move towards auto-import
This commit is contained in:
87
Stars Assistant/CSV/PlanetLoader.cs
Normal file
87
Stars Assistant/CSV/PlanetLoader.cs
Normal file
@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using CsvHelper.Configuration;
|
||||
using CsvHelper;
|
||||
using System.Globalization;
|
||||
using Splat;
|
||||
|
||||
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 = new Model.Planet{ Name = csvp.Name };
|
||||
csvp.UpdateDbPlanet(p);
|
||||
db.Add(p);
|
||||
}
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user