sa/Stars Assistant/Services/PlanetManager.cs

75 lines
2.2 KiB
C#
Raw Permalink Normal View History

using System;
using System.ComponentModel;
using System.Reactive.Linq;
using DynamicData;
using DynamicData.Binding;
using Splat;
using StarsAssistant.Model;
using StarsAssistant.ViewModels;
namespace StarsAssistant.Services;
public class PlanetManager : IDisposable, IEnableLogger
{
protected Services.Game Game = Locator.Current.GetService<Services.Game>()!;
2024-10-02 18:18:00 +00:00
/// <summary>
/// SourceCache for DynamicData views
/// </summary>
private SourceCache<Planet, string> _planets = new(p => p.Name);
2024-10-02 18:18:00 +00:00
/// <summary>
/// Observable changeset showing all player planets converted to view models.
/// </summary>
public IObservable<IChangeSet<PlayerPlanetViewModel, string>> PlayerPlanetsSource
=> _planets
.Connect()
.Filter(planet => planet.OwnerId == Game.Player.Name)
.Transform(planet => new PlayerPlanetViewModel(planet));
public PlanetManager()
{
FleetManager fleetManager = Locator.Current.GetService<FleetManager>()!;
}
2024-10-02 18:18:00 +00:00
/// <summary>
/// Load the planet records from the database and push them into our source cache.
/// </summary>
2024-09-26 20:18:50 +00:00
public void InitFromDatabase()
{
using var db = Locator.Current.GetService<StarsDatabase>()!;
2024-10-02 18:18:00 +00:00
var allPlanets = db.Planet.ToList();
2024-10-04 17:05:23 +00:00
var cacheKeys = _planets.Keys.ToList();
var planetNames = from p in allPlanets select p.Name;
var planetsToDelete = cacheKeys.Except(planetNames);
_planets.Edit(innerCache =>
{
foreach (var name in planetsToDelete)
innerCache.RemoveKey(name);
innerCache.AddOrUpdate(allPlanets);
}
);
}
/// <summary>
/// Handle disposal of all subscriptions and dependencies.
/// </summary>/
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_planets.Dispose();
}
}
/// <summary>
/// Boilerplate disposal
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}