sa/Stars Assistant/CSV/FleetLoader.cs

78 lines
2.3 KiB
C#
Raw Normal View History

using System;
using System.Diagnostics.CodeAnalysis;
using CsvHelper.Configuration;
using CsvHelper;
using System.Globalization;
using Splat;
using StarsAssistant.Services;
using Avalonia.Animation;
namespace StarsAssistant.CSV;
public class FleetLoader
{
/// <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 FleetLoader()
{
CreateConfig();
}
/// <summary>
/// Creates the CSV configuration for planets.
/// </summary>
[MemberNotNull(nameof(CsvConfig))]
protected void CreateConfig()
{
CsvConfig = CsvConfiguration.FromAttributes<Fleet>(CultureInfo.InvariantCulture);
CsvConfig.Delimiter = "\t";
CsvConfig.Escape = '\0';
CsvConfig.MissingFieldFound = null;
}
/// <summary>
/// Import the fleet file for the given Race, all other records will be ignored.
/// Since we can't update existing records, we will delete all applicable ones
/// before inserting new Fleets.
/// </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.FleetFileForRace(race), System.Text.Encoding.Latin1);
using var csv = new CsvReader(reader, CsvConfig);
var oldFleetsToDelete = from flt in db.Fleet
where flt.OwnerFileId == race.PlayerFileId
select flt;
db.RemoveRange(oldFleetsToDelete);
List<CSV.Fleet> records = csv.GetRecords<Fleet>().ToList();
var fleetsForPlayer = from flt in records
where flt.OwnerFileId == race.PlayerFileId
select flt;
foreach (var csvFleet in fleetsForPlayer)
{
Model.Fleet dbFleet = new();
csvFleet.UpdateDbFleet(dbFleet);
dbFleet.OwnerId = race.Name;
db.Add(dbFleet);
}
db.SaveChanges();
}
}