using System.Collections.Generic;
using Verse;
using RimWorld;
using System.Linq;

namespace rjw
{
	public static class SurgeryHelper
	{
		// Quick and dirty method to guess whether the player is harvesting the genitals or amputating them
		// due to infection. The core code can't do this properly because it considers the private part
		// hediffs as "unclean".
		public static bool IsHarvest(Pawn p, BodyPartRecord part)
		{
			foreach (Hediff hed in p.health.hediffSet.hediffs)
			{
				if ((hed.Part?.def == part.def) && hed.def.isBad && (hed.Severity >= 0.70f))
					return false;
			}
			return true;
		}

		/// <summary>
		/// Spawn a part from its hediff and do the same for all sub-parts (unless we're on the main body part). 
		/// Also removes part hediffs so the BodyPartRecord can count as 'clean' for the purposes of core part spawning logic.
		/// </summary>
		/// <remarks>
		/// This is currently overkill as parts are forced to only appear on specific BodyPartRecords without sub-parts, 
		/// but hopefully someday someone will make a submod featuring a race with dicktongued mouth-pussies or something
		/// and then you will see.
		/// <para>Then you will all see.</para>
		/// </remarks>
		public static void RemoveAndSpawnSexParts(Pawn surgeon, Pawn patient, BodyPartRecord part, bool isReplacement)
		{
			List<Hediff> parts = patient.health.hediffSet.hediffs.Where(h => h.part == part && h is ISexPartHediff).ToList();
			foreach (var partHediff in parts)
			{
				Thing removedPart = SexPartAdder.recipePartRemover(partHediff);
				patient.health.RemoveHediff(partHediff);

				if (removedPart != null)
				{
					if (surgeon?.Map != null)
					{
						GenSpawn.Spawn(removedPart, surgeon.Position, surgeon.Map);
					}
					else if (patient.Map != null)
					{
						GenSpawn.Spawn(removedPart, patient.Position, patient.Map);
					}
				}

				if (isReplacement)
				{
					partHediff.Notify_SurgicallyReplaced(surgeon);
				}
				else
				{
					partHediff.Notify_SurgicallyRemoved(surgeon);
				}
			}

			if (part.IsCorePart)
			{
				return;
			}

			foreach (var subPart in part.parts)
			{
				RemoveAndSpawnSexParts(surgeon, patient, subPart, isReplacement);
			}
		}
	
	}
}