using EDPlayerJournal.Entries;

namespace EDPlayerJournal.BGS;

internal class MarketSellParser : ITransactionParserPart {
    public void Parse(Entry e, TransactionParserContext context, TransactionParserOptions options, TransactionList transactions) {
        long profit = 0;

        if (context.StationOwner == null) {
            transactions.AddIncomplete(
                new SellCargo(),
                "Could not discern the station owner market sell.",
                e);
            return;
        }

        // Ignore if its a fleet carrier faction.
        if (string.Compare(context.StationOwner, Factions.FleetCarrier, StringComparison.OrdinalIgnoreCase) == 0 &&
            options.IgnoreFleetCarrierFaction) {
            return;
        }

        MarketSellEntry? entry = e as MarketSellEntry;
        if (entry == null) {
            throw new NotImplementedException();
        }

        if (entry.Type == null) {
            throw new InvalidJournalEntryException("market sell contains no cargo type");
        }

        if (context.BuyCost.ContainsKey(entry.Type)) {
            long avg = context.BuyCost[entry.Type];
            profit = (long)entry.TotalSale - (avg * entry.Count);
        }

        transactions.Add(new SellCargo(entry) {
            System = context.CurrentSystem,
            Station = context.CurrentStation,
            Faction = context.StationOwner,
            Profit = profit,
            IsLegacy = context.IsLegacy,
        });
    }
}
