using System.Text;
using EDPlayerJournal.Entries;

namespace EDPlayerJournal.BGS; 
public class SellCargo : Transaction {
    public long Profit { get; set; }

    public SellCargo() { }

    public SellCargo(MarketSellEntry e) {
        Entries.Add(e);
    }

    public string? Cargo {
        get {
            string? cargo;
            var sell = Entries.OfType<MarketSellEntry>().First();

            if (!string.IsNullOrEmpty(sell.TypeLocalised)) {
                cargo = sell.TypeLocalised;
            } else {
                cargo = sell.Type;
                if (cargo != null && cargo.Length >= 2) {
                    cargo = cargo[0].ToString().ToUpper() + cargo.Substring(1);
                }
            }

            return cargo;
        }
    }

    public string Market {
        get {
            var sell = Entries.OfType<MarketSellEntry>().First();
            return sell.BlackMarket ? "Black Market" : "Commodity Market";
        }
    }

    public long Amount {
        get { return Entries.OfType<MarketSellEntry>().Sum(x => x.Count); }
    }

    public override string ToString() {
        StringBuilder builder = new StringBuilder();
        var sold = Entries.OfType<MarketSellEntry>().ToArray();

        if (sold == null || sold.Length == 0) {
            return builder.ToString();
        }

        foreach (MarketSellEntry sell in sold) {
            builder.AppendFormat("Sold {0} {1} to the {2} of {3}",
                sell.Count,
                Cargo,
                Market,
                Station
                );

            if (Profit != 0) {
                builder.AppendFormat(" ({0} {1})",
                    Credits.FormatCredits(Profit),
                    Profit < 0 ? "loss" : "profit"
                    );
            }
        }

        return builder.ToString().Trim();
    }

    /// <summary>
    /// Selling resources to a market only helps the controlling faction
    /// </summary>
    public override bool OnlyControllingFaction => true;
}