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

namespace rjw
{
	public class Recipe_AddMultiPart : Recipe_InstallPart
	{
		// Record tale without removing pre-existing parts
		protected override void OnSurgerySuccess(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
		{
			if (billDoer != null)
			{
				TaleRecorder.RecordTale(TaleDefOf.DidSurgery, billDoer, pawn);
			}
		}

		protected override bool CanApplyOnPart(Pawn pawn, BodyPartRecord record)
		{
			return base.CanApplyOnPart(pawn, record) && !pawn.health.hediffSet.PartIsMissing(record);
		}

		public override bool ValidFor(Pawn pawn)
		{
			if (!base.ValidFor(pawn))
			{
				return false;
			}

			var parts = pawn.GetGenitalsList();
			GenitalFamily? genitalType = (recipe.addsHediff as HediffDef_SexPart).genitalFamily;

			//don't add if artificial parts present
			if (pawn.health.hediffSet.hediffs.Any((Hediff hed) =>
				(hed.Part != null) && recipe.appliedOnFixedBodyParts.Contains(hed.Part.def) && hed is Hediff_AddedPart))
			{
				return false;
			}

			return true;
		}

		public override IEnumerable<BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
		{
			//don't add if artificial parts present
			foreach (var part in base.GetPartsToApplyOn(pawn, recipe))
			{
				if (pawn.health.hediffSet.GetDirectlyAddedPartFor(part)?.def.organicAddedBodypart ?? true)
				{
					yield return part;
				}
			}
		}
	}
}
