using System.Collections.Generic;
using System.Text;
using EDPlayerJournal.Entries;

namespace EDPlayerJournal.BGS;

public class MissionCompleted : Transaction {
    public MissionCompletedEntry? CompletedEntry { get; set; }

    public MissionAcceptedEntry? AcceptedEntry { get; set; }

    public Mission? Mission { get; set; }

    public MissionCompleted() { }

    public override DateTime? CompletedAtDateTime {
        get {
            if (CompletedEntry == null) {
                return null;
            }
            return CompletedEntry.Timestamp;
        }
    }

    public string MissionName {
        get {
            if (CompletedEntry == null || CompletedEntry.Mission == null) {
                return "";
            }

            return CompletedEntry.Mission.FriendlyName;
        }
    }

    public string Influence {
        get {
            if (CompletedEntry == null || Faction == null || CompletedEntry.Mission == null) {
                return "";
            }

            return string.Join("",
                CompletedEntry
                .Mission
                .GetInfluenceForFaction(Faction, SystemAddress)
                .Select(x => x.Influence)
                .ToArray()
                )
                ;
        }
    }

    /// <summary>
    /// Rescue missions contribute to the system.
    /// </summary>
    public override bool SystemContribution {
        get {
            if (Mission == null || Mission.Name == null) {
                return false;
            }

            // If the mission starts with the name for thargoid war mission
            // names, we assume its a system contribution
            if (Mission.Name.Contains("Mission_TW_")) {
                return true;
            }

            return false;
        }
    }

    public override string ToString() {
        if (Faction == null || CompletedEntry == null || CompletedEntry.Mission == null) {
            return "";
        }

        StringBuilder builder = new StringBuilder();
        var influence = CompletedEntry.Mission.GetInfluenceForFaction(Faction, SystemAddress);

        builder.AppendFormat("{0}", MissionName);
        if (influence != null && influence.Length > 0) {
            builder.AppendFormat(", Influence: {0}", 
                influence.Select(x => x.InfluenceAmount).Sum()
                );
        }

        return builder.ToString();
    }
}
