using System;
using System.Runtime.InteropServices;
using Windows.Graphics.Capture;

namespace ytLive.Services;

/// <summary>
/// Desktop-interop bridges for Graphics Capture that CsWinRT can't project:
/// creating a <see cref="GraphicsCaptureItem"/> from an HMONITOR/HWND via the
/// activation factory's IGraphicsCaptureItemInterop, and wiring the
/// GraphicsCapturePicker to an owner window via IInitializeWithWindow.
/// GUIDs and signatures come from the official Windows GraphicsCapture samples.
/// </summary>
internal static class CaptureInterop
{
    private static readonly Guid GraphicsCaptureItemGuid = new("79C3F95B-31F7-4EC2-A464-632EF5D30760");

    public static GraphicsCaptureItem CreateForMonitor(IntPtr hmonitor)
    {
        var interop = GraphicsCaptureItem.As<IGraphicsCaptureItemInterop>();
        return GraphicsCaptureItem.FromAbi(interop.CreateForMonitor(hmonitor, GraphicsCaptureItemGuid));
    }

    public static GraphicsCaptureItem CreateForWindow(IntPtr hwnd)
    {
        var interop = GraphicsCaptureItem.As<IGraphicsCaptureItemInterop>();
        return GraphicsCaptureItem.FromAbi(interop.CreateForWindow(hwnd, GraphicsCaptureItemGuid));
    }

    public static void SetWindowOwner(GraphicsCapturePicker picker, IntPtr hwnd)
    {
        var interop = (IInitializeWithWindow)(object)picker;
        interop.Initialize(hwnd);
    }

    [ComImport]
    [Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    private interface IGraphicsCaptureItemInterop
    {
        IntPtr CreateForWindow([In] IntPtr window, [In] ref Guid iid);
        IntPtr CreateForMonitor([In] IntPtr monitor, [In] ref Guid iid);
    }

    [ComImport]
    [Guid("3E68D4BD-7135-4D10-8018-9FB6D9F33FA1")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    private interface IInitializeWithWindow
    {
        void Initialize(IntPtr hwnd);
    }
}
