using System; using System.ComponentModel; using System.Reactive.Linq; using System.Text.RegularExpressions; using DynamicData; using DynamicData.Binding; using Splat; using StarsAssistant.Model; using StarsAssistant.ViewModels; namespace StarsAssistant.Services; public class FleetManager { protected Services.Game Game = Locator.Current.GetService()!; /// /// SourceCache for DynamicData views /// private SourceCache _fleets = new(f => f.Id); public FleetManager() {} public class FleetSummary { public string Destination { get; set; } = string.Empty; public int TotalIronium { get; set; } public int TotalBoranium { get; set; } public int TotalGermanium { get; set; } public int TotalColonists { get; set; } } private IObservable>? _fleetSummaries; public void test() { /* _fleetSummaries = _fleets.Connect() .Group(fleet => fleet.TrueDestination) .Transform(grouping => new FleetSummary { Destination = grouping.Key, TotalIronium = grouping.Items.Sum(f => f.Ironium), TotalBoranium = grouping.Items.Sum(f => f.Boranium), TotalGermanium = grouping.Items.Sum(f => f.Germanium), TotalColonists = grouping.Items.Sum(f => f.Colonists) }) .Sort(SortExpressionComparer.Ascending(f => f.Planet)) .AsObservableChangeSet(summary => summary.Planet); */ } /// /// Load the fleet records from the database and push them into our source cache. /// If the data has been freshly imported, call PostProcessImportedData first. /// public void InitFromDatabase() { using var db = Locator.Current.GetService()!; var allFleets = db.Fleet.ToList(); _fleets.Edit(innerCache => { innerCache.Clear(); innerCache.AddOrUpdate(allFleets); } ); } /// /// Helper to fill up missing data from the original import. Tries to deduce /// missing properties using heuristics. /// public static void PostProcessImportedData() { using var db = Locator.Current.GetService()!; // Check for all cases where we're targeting another fleet instead of // a planet. Update the DB accordingly. var playerFleets = from flt in db.Fleet where flt.OwnerFileId == Game.Player.PlayerFileId select flt; Regex shipPattern = new ($@"^{Regex.Escape(Game.Player.Name)} (?.+) #\d+$"); foreach (Fleet flt in playerFleets) { if (flt.Destination != "-- ") { var trueDest = db.Fleet .FirstOrDefault(f => f.FleetName == $"{Game.Player.Name} {flt.Destination}" && f.Planet != String.Empty); flt.TrueDestination = trueDest?.Planet ?? flt.Destination; } else { flt.TrueDestination = "-- "; } Match m = shipPattern.Match(flt.FleetName); if (m.Success) flt.ShipTypeGuess = m.Groups[1].Value; db.Update(flt); } db.SaveChanges(); } }