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 { /// /// Reference to the game metadata, retrieved by DI /// protected Services.Game Game = Locator.Current.GetService()!; /// /// CSV Configuration to use for importing Planet files. /// protected CsvConfiguration CsvConfig; /// /// Construction /// public FleetLoader() { CreateConfig(); } /// /// Creates the CSV configuration for planets. /// [MemberNotNull(nameof(CsvConfig))] protected void CreateConfig() { CsvConfig = CsvConfiguration.FromAttributes(CultureInfo.InvariantCulture); CsvConfig.Delimiter = "\t"; CsvConfig.Escape = '\0'; CsvConfig.MissingFieldFound = null; } /// /// 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. /// /// Import File public void ImportForRace(Model.Race race) { using var db = Locator.Current.GetService()!; 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 records = csv.GetRecords().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(); } }