using System.Text.Json; using XFEEDToolBox.Core.Models; namespace XFEEDToolBox.Core.Data; public sealed class FleetProjector { private readonly Dictionary known = []; private HashSet? listed; public long? CurrentShipId { get; private set; } public DateTimeOffset? FleetAt { get; private set; } public DateTimeOffset? StoredModulesAt { get; private set; } public IReadOnlyList StoredModules { get; private set; } = []; public IReadOnlyList Ships => known.Values.Where(s => listed is null || listed.Contains(s.ShipId) || s.ShipId == CurrentShipId).OrderByDescending(s => s.ShipId == CurrentShipId).ThenBy(s => s.Type).ToArray(); public void Reset() { known.Clear(); listed = null; CurrentShipId = null; FleetAt = StoredModulesAt = null; StoredModules = []; } public void Apply(JsonElement e, string currentSystem) { var kind = e.Text("event"); var time = e.Time() ?? DateTimeOffset.MinValue; switch (kind) { case "LoadGame": CurrentShipId = e.Get("ShipID").ValueKind == JsonValueKind.Number ? e.Long("ShipID") : CurrentShipId; break; case "Loadout": var id = e.Long("ShipID", -1); if (id < 0) return; var prior = known.GetValueOrDefault(id) ?? new ShipRecord { ShipId = id }; if (prior.ConfigurationAt > time || prior.ConfigurationChanged && prior.LastSeen > time) return; known[id] = prior with { Type = e.Text("Ship"), Name = e.Text("ShipName").Trim(), Ident = e.Text("ShipIdent"), CargoCapacity = e.Get("CargoCapacity").ValueKind == JsonValueKind.Number ? (int)e.Long("CargoCapacity") : null, UnladenMass = e.Number("UnladenMass"), MaxJumpRange = e.Number("MaxJumpRange"), HullHealth = e.Number("HullHealth"),HullHealthAt=e.Number("HullHealth") is null?null:time, FuelMain = e.Get("FuelCapacity").Number("Main"), FuelReserve = e.Get("FuelCapacity").Number("Reserve"), Rebuy = e.Number("Rebuy") is { } rebuy ? (decimal)rebuy : prior.Rebuy, Hot = e.Flag("Hot"), SystemName = currentSystem.Length > 0 ? currentSystem : prior.SystemName, Modules = e.Get("Modules").Items().Select(ParseModule).ToArray(), ConfigurationAt = time, ConfigurationChanged = false, LastSeen = time }; CurrentShipId = id; listed?.Add(id); break; case "HullDamage" when e.Flag("PlayerPilot")&&!e.Flag("Fighter")&&CurrentShipId is {} damaged&&known.TryGetValue(damaged,out var hullShip) &&e.Number("Health") is {} health&&double.IsFinite(health)&&health is >=0 and <=1&&!(hullShip.HullHealthAt>time): known[damaged]=hullShip with{HullHealth=health,HullHealthAt=time}; break; case "StoredShips": if (FleetAt > time) return; if (e.Get("ShipsHere").ValueKind != JsonValueKind.Array || e.Get("ShipsRemote").ValueKind != JsonValueKind.Array) return; listed = []; foreach (var item in e.Get("ShipsHere").Items().Concat(e.Get("ShipsRemote").Items())) { var storedId = item.Long("ShipID", -1); if (storedId < 0) continue; listed.Add(storedId); var old = known.GetValueOrDefault(storedId) ?? new ShipRecord { ShipId = storedId }; known[storedId] = old with { Type = item.Text("ShipType_Localised", item.Text("ShipType", old.Type)), Name = item.Text("Name", old.Name), SystemName = item.Text("StarSystem", e.Text("StarSystem")), MarketId = item.Long("ShipMarketID", e.Long("MarketID")), Hot = item.Flag("Hot"), InTransit = item.Flag("InTransit"), Value = item.Long("Value"), TransferPrice = item.Number("TransferPrice") is { } price ? (long)price : null, TransferSeconds = item.Number("TransferTime") is { } seconds ? (int)seconds : null, LastSeen = time }; } FleetAt = time; break; case "StoredModules": if (StoredModulesAt > time) return; if (e.Get("Items").ValueKind != JsonValueKind.Array) return; StoredModules = e.Get("Items").Items().Select(x => new StoredModule { Item = x.Text("Name"), Name = x.Text("Name_Localised", x.Text("Name")), StorageSlot = x.Long("StorageSlot"), SystemName = x.Text("StarSystem"), MarketId = x.Long("MarketID"), BuyPrice = x.Long("BuyPrice"), TransferCost = x.Long("TransferCost"), TransferTime = (int)x.Long("TransferTime"), Hot = x.Flag("Hot"), InTransit = x.Flag("InTransit"), Engineering = x.Text("EngineeringModifications", x.Text("EngineerModifications")), EngineeringLevel = x.Number("Level") is { } level ? (int)level : null, EngineeringQuality = x.Number("Quality"), ObservedAt = time }).ToArray(); StoredModulesAt = time; break; case "ShipyardNew": var newId = e.Long("NewShipID", -1); if (newId < 0) return; known[newId] = new() { ShipId = newId, Type = e.Text("ShipType"), SystemName = currentSystem, LastSeen = time }; listed?.Add(newId); CurrentShipId = newId; break; case "ShipyardSell": var sold = e.Long("SellShipID", e.Long("ShipID", -1)); known.Remove(sold); listed?.Remove(sold); break; case "ShipyardSwap": CurrentShipId = e.Long("ShipID"); // StoreOldShip is the ship type (e.g. "Anaconda"), not a flag. if (e.Long("StoreShipID", -1) is >= 0 and var storedOld) { var previousShip = known.GetValueOrDefault(storedOld) ?? new ShipRecord { ShipId = storedOld }; known[storedOld] = previousShip with { Type = previousShip.Type.Length > 0 ? previousShip.Type : e.Text("StoreOldShip"), SystemName = currentSystem.Length > 0 ? currentSystem : previousShip.SystemName, MarketId = e.Long("MarketID") is > 0 and var storedAt ? storedAt : previousShip.MarketId, InTransit = false, TransferPrice = null, TransferSeconds = null, LastSeen = time }; listed?.Add(storedOld); } break; case "Location": case "FSDJump": case "CarrierJump": case "Docked": if (CurrentShipId is { } active && known.TryGetValue(active, out var ship)) known[active] = ship with { SystemName = e.Text("StarSystem", currentSystem), MarketId = e.Long("MarketID") is > 0 and var mid ? mid : null, LastSeen = time }; break; case "Undocked": if (CurrentShipId is { } departed && known.TryGetValue(departed, out var departingShip)) known[departed] = departingShip with { MarketId = null, LastSeen = time }; break; case "EngineerCraft": var craftShip = e.Long("ShipID", CurrentShipId ?? -1); if (!known.TryGetValue(craftShip, out var craftConfig) || craftConfig.ConfigurationAt > time) break; var modules = craftConfig.Modules.ToArray(); var moduleIndex = Array.FindIndex(modules, m => m.Slot == e.Text("Slot") && m.Item.Equals(e.Text("Module"), StringComparison.OrdinalIgnoreCase)); if (moduleIndex < 0) { known[craftShip] = craftConfig with { ConfigurationChanged = true, LastSeen = time }; break; } var previousEngineering = modules[moduleIndex].Engineering; var unchangedBlueprint = previousEngineering?.Blueprint == e.Text("BlueprintName"); modules[moduleIndex] = modules[moduleIndex] with { Engineering = new() { Engineer = e.Text("Engineer"), Blueprint = e.Text("BlueprintName"), Level = (int)e.Long("Level"), Quality = e.Number("Quality"), ExperimentalEffectId = e.Text("ApplyExperimentalEffect", unchangedBlueprint ? previousEngineering!.ExperimentalEffectId : ""), ExperimentalEffect = e.Text("ApplyExperimentalEffect_Localised", e.Text("ApplyExperimentalEffect", unchangedBlueprint ? previousEngineering!.ExperimentalEffect : "")), Modifiers = e.Get("Modifiers").ValueKind == JsonValueKind.Array ? ParseModifiers(e.Get("Modifiers")) : previousEngineering?.Modifiers ?? [] } }; known[craftShip] = craftConfig with { Modules = modules, LastSeen = time }; break; case "ModuleBuy": case "ModuleSell": case "ModuleSwap": case "ModuleStore": case "ModuleRetrieve": case "EngineerLegacyConvert": case "MassModuleStore": case "ModuleSellRemote": if (kind == "EngineerLegacyConvert" && e.Flag("IsPreview")) break; var changed = e.Long("ShipID", CurrentShipId ?? -1); if (known.TryGetValue(changed, out var configuration)) known[changed] = configuration with { ConfigurationChanged = true, LastSeen = time }; break; } } public static FittedModule ParseModule(JsonElement m) => new() { Slot = m.Text("Slot"), Item = m.Text("Item"), Name = m.Text("Item_Localised", m.Text("Item")), Enabled = m.Flag("On"), Priority = (int)m.Long("Priority"), Health = m.Number("Health"), Value = m.Number("Value") is { } v ? (long)v : null, AmmoInClip = m.Number("AmmoInClip") is { } clip ? (int)clip : null, AmmoInHopper = m.Number("AmmoInHopper") is { } hopper ? (int)hopper : null, Engineering = m.Get("Engineering") is { ValueKind: JsonValueKind.Object } eng ? new() { Engineer = eng.Text("Engineer"), Blueprint = eng.Text("BlueprintName"), Level = (int)eng.Long("Level"), Quality = eng.Number("Quality"), ExperimentalEffect = eng.Text("ExperimentalEffect_Localised", eng.Text("ExperimentalEffect")), ExperimentalEffectId = eng.Text("ExperimentalEffect"), Modifiers = ParseModifiers(eng.Get("Modifiers")) } : null }; private static IReadOnlyList ParseModifiers(JsonElement array) => array.Items().Select(x => new EngineeringModifier(x.Text("Label"), x.Number("Value"), x.Number("OriginalValue"), x.Flag("LessIsGood"), x.Text("ValueStr"))).ToArray(); }