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

namespace EliteBGS.BGS {
    public class SellCargo : LogEntry {
        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.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}",
                    sell.Count,
                    Cargo,
                    Market
                    );

                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;
    }
}