using System.Text;
using EDPlayerJournal.Entries;

namespace EDPlayerJournal.BGS; 

public class BuyCargo : Transaction {
    public BuyCargo() { }

    public BuyCargo(MarketBuyEntry e) {
        Entries.Add(e);
    }

    public string? Cargo {
        get {
            string? cargo;
            var sell = Entries.OfType<MarketBuyEntry>().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 long Amount {
        get { return Entries.OfType<MarketBuyEntry>().Sum(x => x.Count); }
    }

    public override int CompareTo(Transaction? other) {
        if (other == null || other.GetType() != typeof(BuyCargo)) {
            return -1;
        }

        BuyCargo? buycargo = other as BuyCargo;
        if (buycargo != null &&
            buycargo.Cargo == Cargo &&
            buycargo.System == System &&
            buycargo.Faction == Faction) {
            return 0;
        }

        return -1;
    }

    public override string ToString() {
        StringBuilder builder = new StringBuilder();

        if (Entries.Count <= 0) {
            return builder.ToString();
        }

        builder.AppendFormat("Bought {0} {1} at the Commodity Market",
            Amount,
            Cargo
            );

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

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