using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace NexusShell.Services;

internal static class EvidenceScreenshotService
{
    public static async Task CaptureAsync(Window window, string outputPath)
    {
        await window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.Render);
        await Task.Delay(400);

        await window.Dispatcher.InvokeAsync(() =>
        {
            window.UpdateLayout();
            var width = (int)Math.Max(1, window.ActualWidth);
            var height = (int)Math.Max(1, window.ActualHeight);

            var bitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(window);

            var directory = Path.GetDirectoryName(outputPath);
            if (!string.IsNullOrWhiteSpace(directory))
            {
                Directory.CreateDirectory(directory);
            }

            using var stream = File.Create(outputPath);
            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(stream);
        });
    }
}
