using System;
using System.Collections.Generic;
using System.Linq;
using Verse;
using UnityEngine;
using RimWorld;
using HarmonyLib;
using System.Reflection;
using System.Reflection.Emit;

namespace ColorBlindJoh
{
	[StaticConstructorOnStartup]
	static class JohColorBlind{
		// Constructor for this patch
		// Im assuming it gets called somewhere
		static JohColorBlind(){
			var harmonyInstance = new Harmony("com.naka.rimworld.colorblindjoh");
			harmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
			Log.Message(
				"Joh better not be colorblind no more"
			);
		}

		[HarmonyPatch(typeof(FertilityGrid), "CellBoolDrawerGetExtraColorInt", new Type[] { typeof(int) })]
		static class Patch_FertilityGrid
		{
			static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{

				// Turn instructions enumerable into a list
				var instructionsList = instructions.ToList();

				Log.Message(
					"Yo im stolen all of erin's H's"
				);

				for (var i = 0; i < instructionsList.Count; i++)
				{

					CodeInstruction instruction = instructionsList[i];

					// Target the specific line of code that sets the color to "MediumFertilityClor"
					if (
						instruction.opcode == OpCodes.Ldsfld
						&& instruction.operand.ToString() == "UnityEngine.Color HighFertilityColor"
					)
					{
						// Change it to Unity.color.blue
						yield return new CodeInstruction(OpCodes.Call, typeof(Patch_FertilityGrid).GetMethod("AlternateColor"));
					}
					else
					{
						yield return instruction;
					}
				}
			}

			// Change the color
			public static Color AlternateColor()
			{
				Log.Message(
					"Turn blue, D*ckhead"
				);
				return Color.blue;
			}
		}
	}

}
