using System.Collections.Generic;
using System.Linq;
using Verse;
using RimWorld;
using rjw.Modules.Shared.Logs;
using System.Diagnostics;

namespace SCE
{
    public class RitualObligationTargetWorker_MarriageSpotOrAltar : RitualObligationTargetFilter
    {
        public RitualObligationTargetWorker_MarriageSpotOrAltar() {  }

		public RitualObligationTargetWorker_MarriageSpotOrAltar(RitualObligationTargetFilterDef def)
			: base(def) {  }

        public override IEnumerable<TargetInfo> GetTargets(RitualObligation obligation, Map map)
        {
            var marriageSpots = map.listerBuildings.AllBuildingsColonistOfDef(ThingDefOf.MarriageSpot);
            foreach (var spot in marriageSpots)
            {
                yield return spot;
            }

            foreach (TargetInfo altar in RitualObligationTargetWorker_Altar.GetTargetsWorker(obligation, map, parent.ideo))
            {
                yield return altar;
            }
        }

		protected override RitualTargetUseReport CanUseTargetInternal(TargetInfo target, RitualObligation obligation)
        {
			if (!target.HasThing)
				return false;
			
			var thing = target.Thing;
			if (def.colonistThingsOnly && (thing.Faction == null || !thing.Faction.IsPlayer))
				return false;
			
			if (thing.def == ThingDefOf.MarriageSpot)
				return true;
			
            var compGatherSpot = thing.TryGetComp<CompGatherSpot>();
			if (compGatherSpot != null && compGatherSpot.Active)
				return true;
			
            return RitualObligationTargetWorker_Altar.CanUseTargetWorker(target, obligation, parent.ideo);
        }

		public override IEnumerable<string> GetTargetInfos(RitualObligation obligation)
        {
            yield return ThingDefOf.MarriageSpot.LabelCap;
			foreach (var info in RitualObligationTargetWorker_Altar.GetTargetInfosWorker(parent.ideo))
			    yield return info;
        }

        public override string LabelExtraPart(RitualObligation obligation)
        {
            if (obligation == null)
            {
                if (SCESettings.debugMode)
                {
                    int errHash = parent.GetHashCode() ^ (parent.activeObligations.Count << 3);
                    Log.ErrorOnce($"Attempted to generate LabelExtraPart for {parent.Label} with a null obligation", errHash++);
                    Log.ErrorOnce("Listing existing obligations: ", errHash++);
                    Log.ErrorOnce(parent.activeObligations.Select(
                            ob => $"- precept={ob.precept?.Label}, targetA={ob.targetA.Thing?.Label}, targetB={ob.targetB.Thing?.Label}").ToLineList(), errHash++);
                }
                return "";
            }
            var firstPawn = (Pawn) obligation.targetA;
            var secondPawn = (Pawn) obligation.targetB;
            return $"{firstPawn.LabelShort} and {secondPawn.LabelShort}";
        }
    }
}