using System.Linq;
using System.Text;
using System.Windows.Documents;
using EDPlayerJournal;
using EDPlayerJournal.BGS;

namespace EliteBGS.LogGenerator;

public class CargoSoldFormatter : LogFormatter {
    public string GenerateLog(Objective objective) {
        StringBuilder builder = new StringBuilder();
        SellCargo[] sold = objective.EnabledOfType<SellCargo>().ToArray();

        if (sold == null || sold.Length <= 0) {
            return "";
        }


        // This groups everything together by cargo sold, and then by market sold to.
        //  Dictionary<string Cargo, Dictionary<string Market, { Market, Amount, Profit }> >
        var entries = sold.GroupBy(x => x.Cargo,
                                   (key, cargos) => new {
                                       Cargo = key,
                                       Markets = cargos.GroupBy(y => y.Market,
                                                           (market, markets) => new {
                                                               Market = market,
                                                               Amount = markets.Sum(x => x.Amount),
                                                               Profit = markets.Sum(x => x.Profit)
                                                           })
                                   }
                                   )
                          ;

        foreach (var cargo in entries) {
            foreach (var market in cargo.Markets) {
                builder.AppendFormat("Sold {0} {1} to the {2}",
                        market.Amount,
                        cargo.Cargo,
                        market.Market
                    );

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

                builder.Append("\n");
            }
        }

        builder.AppendFormat("\n");

        return builder.ToString();
    }

    public string GenerateSummary(Objective objective) {
        SellCargo[] sold = objective.EnabledOfType<SellCargo>().ToArray();
        long totalProfit = sold.Sum(x => x.Profit);
        long tons = sold.Sum(x => x.Amount);

        if (tons <= 0) {
            return "";
        }

        StringBuilder builder = new();

        builder.Append("Sold: ");
        builder.AppendFormat("{0}t", tons);
        if (totalProfit >= 100000) {
            builder.AppendFormat(", {0} profit", Credits.FormatMillions(totalProfit));
        }

        return builder.ToString();
    }
}
