﻿using RimWorld;
using Verse;
using HarmonyLib;
using System.Reflection;
using System.Collections.Generic;

/// <summary>
/// Modifies Dialog_NamePawn so it properly displays same-gender parents in their children’s rename window
/// </summary>
namespace rjw
{
	[HarmonyPatch(typeof(Dialog_NamePawn))]
	[HarmonyPatch(MethodType.Constructor)]
	[HarmonyPatch(new System.Type[] {
	typeof(Pawn),
	typeof(NameFilter),
	typeof(NameFilter),
	typeof(Dictionary<NameFilter, List<string>>),
	typeof(string),
	typeof(string),
	typeof(string),
	typeof(string)})]
	static class patch_Dialog_NamePawn
	{
		static AccessTools.FieldRef<Dialog_NamePawn, TaggedString> descriptionTextRef = AccessTools.FieldRefAccess<Dialog_NamePawn, TaggedString>("descriptionText");
		static MethodInfo DescribePawn = AccessTools.Method(typeof(Dialog_NamePawn), nameof(DescribePawn));

		[HarmonyPostfix]
		static void Constructor(Dialog_NamePawn __instance)
		{
			string motherString = "Mother";
			string fatherString = "Father";
			Pawn pawn = __instance.pawn;

			if (pawn != null && pawn.RaceProps.Humanlike)
			{
				Pawn mother = pawn.GetMother();
				Pawn father = pawn.GetFather();
				if (father == null && mother == null) return; // this code makes no sense if both failed, idk if this can happen

				Pawn parent = RelationChecker.getParent(pawn);
				Pawn secondParent = RelationChecker.getSecondParent(pawn);
				if (parent != null && secondParent != null && (mother == null || father == null)) // same gender parents
				{
					if (father == null)
					{
						fatherString = "Mother"; // feel free to replace with any more fitting term
						father = mother == parent ? secondParent : parent;
					}
					if (mother == null)
					{
						motherString = "Father";
						mother = father == parent ? secondParent : parent;
					}

					descriptionTextRef(__instance) =
						"{0}: {1}\n{2}: {3}".Formatted(
							motherString.Translate().CapitalizeFirst(),
							(TaggedString)DescribePawn.Invoke(__instance, [mother]),
							fatherString.Translate().CapitalizeFirst(),
							(TaggedString)DescribePawn.Invoke(__instance, [father]));
				}
			}
		}
	}
}
