using System.Text;
using System.Linq;
using EDJournal;

namespace EliteBGS.BGS {
    public class BuyCargo : LogEntry {
        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.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(LogEntry other) {
            if (other == null || other.GetType() != typeof(BuyCargo)) {
                return -1;
            }

            BuyCargo buycargo = other as BuyCargo;
            if (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;
    }
}