using HarmonyLib;
using Telerik.WinControls.UI;

namespace Pilz.UI.Telerik.Patches.TelerikUiForWinForms;

[HarmonyPatch(typeof(RadPictureBoxElement))]
[HarmonyPatch("PasteImage")]
public class RadPictureBoxElement_PasteImageFixes
{
    private static readonly Dictionary<RadPictureBoxElement, Image> images = [];

    public static void Prefix(object __instance)
    {
        if (__instance is RadPictureBoxElement pb)
        {
            // Remember our image
            images.Remove(pb);
            images.Add(pb, pb.Image);
        }
    }

    public static void Postfix(object __instance)
    {
        if (__instance is RadPictureBoxElement pb && images.TryGetValue(pb, out var image))
        {
            // Remove first to avoid conflicts on error
            images.Remove(pb);

            // Call "OnImageLoaded"
            if (pb.Image != image)
                typeof(RadPictureBoxElement).GetMethod("OnImageLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.Invoke(pb, null);
        }
    }
}
