using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace EDPlayerJournal.Entries; 
public class RedeemVoucherEntry : Entry {
    protected override void Initialise() {
        Amount = (JSON.Value<ulong?>("Amount") ?? 0);
        Type = JSON.Value<string>("Type");

        /* according to API, there should be a Factions structure */
        JToken? factions = JSON.GetValue("Factions");
        if (factions != null) {
            foreach (JObject faction in factions.Children<JObject>()) {
                string? faction_name = faction.Value<string>("Faction");
                ulong? faction_bounty = faction.Value<ulong?>("Amount");
                if (faction_name == null || faction_name.Length <= 0 || faction_bounty == null) {
                    continue;
                }
                Factions.Add(faction_name);
                if (!FactionBounties.ContainsKey(faction_name)) {
                    FactionBounties[faction_name] = 0;
                }
                FactionBounties[faction_name] += (faction_bounty ?? 0);
            }
        }

        /* but there also might be just a Faction entry */
        string? single_faction = JSON.Value<string>("Faction");
        if (single_faction != null) {
            Factions.Add(single_faction);
            if (!FactionBounties.ContainsKey(single_faction)) {
                FactionBounties[single_faction] = 0;
            }
            FactionBounties[single_faction] += Amount;
        }
    }

    public ulong GetBountyForFaction(string? a) {
        if (a == null) {
            return 0;
        }

        var relevant = FactionBounties.Where(x => EDPlayerJournal.Factions.CompareFactions(x.Key, a) == 0).ToList();
        if (relevant == null || relevant.Count() == 0) {
            return 0;
        }

        return (ulong)relevant.Sum(x => (decimal)x.Value);
    }

    public ulong Amount { get; set; } = 0;
    public string? Type { get; set; } = "Bounty";

    /// <summary>
    /// List of factions 
    /// </summary>
    public List<string> Factions { get; set; } = new();

    /// <summary>
    /// Bounties awarded by faction
    /// </summary>
    public Dictionary<string, ulong> FactionBounties { get; set; } = new();
}
