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

#pragma warning disable IDE1006 // Naming Styles

namespace AIImages
{
    /// <summary>
    /// Harmony patch to add a gizmo (button) to all colonist pawns
    /// </summary>
    [HarmonyPatch(typeof(Pawn), "GetGizmos")]
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
        "Style",
        "IDE1006:Naming Styles",
        Justification = "RimWorld Harmony patch naming convention"
    )]
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
        "Minor Code Smell",
        "S101:Types should be named in PascalCase",
        Justification = "RimWorld Harmony patch naming convention"
    )]
    public static class Pawn_GetGizmos_Patch
    {
        [HarmonyPostfix]
        public static IEnumerable<Gizmo> Postfix(IEnumerable<Gizmo> __result, Pawn __instance)
        {
            // First, return all original gizmos
            foreach (Gizmo gizmo in __result)
            {
                yield return gizmo;
            }

            // Only add button to colonist pawns that are spawned
            if (
                __instance.IsColonist
                && __instance.Spawned
                && __instance.Faction == Faction.OfPlayer
            )
            {
                yield return new Command_Action
                {
                    defaultLabel = "AIImages.Gizmo.Label".Translate(),
                    defaultDesc = "AIImages.Gizmo.Description".Translate(),
                    icon = ContentFinder<Texture2D>.Get("UI/Commands/AIImage", true),
                    action = delegate()
                    {
                        // Проверяем, открыто ли уже окно AI Image
                        Window_AIImage existingWindow = Find
                            .WindowStack.Windows.OfType<Window_AIImage>()
                            .FirstOrDefault();

                        if (existingWindow != null)
                        {
                            // Если окно открыто, обновляем пешку
                            existingWindow.UpdatePawn(__instance);
                        }
                        else
                        {
                            // Если окна нет, создаём новое
                            Find.WindowStack.Add(new Window_AIImage(__instance));
                        }
                    },
                };
            }
        }
    }
}
