using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Sockets;

namespace ITNexusAgent;

// Läuft als User-Prozess (via schtasks), nicht als SYSTEM-Service
// Captured den Desktop und schickt JPEG-Frames via TCP Loopback an den Service
public static class CaptureModeRunner
{
    private static readonly ImageCodecInfo JpegCodec =
        ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == ImageFormat.Jpeg.Guid);

    public static void Run(string portStr, int screenIdx = 0)
    {
        if (!int.TryParse(portStr, out var port) || port <= 0) return;

        try
        {
            using var tcp = new TcpClient();
            tcp.Connect("127.0.0.1", port);
            var stream = tcp.GetStream();

            var encParams = new EncoderParameters(1);
            encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 60L);

            var allScreens = System.Windows.Forms.Screen.AllScreens;
            Rectangle captureRect;
            if (screenIdx <= 0 || screenIdx > allScreens.Length)
            {
                int left = allScreens.Min(s => s.Bounds.X);
                int top = allScreens.Min(s => s.Bounds.Y);
                int right = allScreens.Max(s => s.Bounds.X + s.Bounds.Width);
                int bottom = allScreens.Max(s => s.Bounds.Y + s.Bounds.Height);
                captureRect = new Rectangle(left, top, right - left, bottom - top);
            }
            else
            {
                captureRect = allScreens[screenIdx - 1].Bounds;
            }

            uint lastHash = 0;
            var sw = System.Diagnostics.Stopwatch.StartNew();

            while (tcp.Connected)
            {
                sw.Restart();
                try
                {
                    using var bmp = new Bitmap(captureRect.Width, captureRect.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    using (var g = Graphics.FromImage(bmp))
                        g.CopyFromScreen(captureRect.X, captureRect.Y, 0, 0, new Size(captureRect.Width, captureRect.Height));

                    var hash = SampleHash(bmp);
                    if (hash == lastHash)
                    {
                        var elapsed = (int)sw.ElapsedMilliseconds;
                        if (elapsed < 16) Thread.Sleep(16 - elapsed);
                        continue;
                    }
                    lastHash = hash;

                    byte[] jpeg;
                    using (var ms = new MemoryStream())
                    {
                        bmp.Save(ms, JpegCodec, encParams);
                        jpeg = ms.ToArray();
                    }

                    stream.Write(BitConverter.GetBytes(jpeg.Length));
                    stream.Write(jpeg);
                    stream.Flush();
                }
                catch { break; }

                var frameMs = (int)sw.ElapsedMilliseconds;
                if (frameMs < 16) Thread.Sleep(16 - frameMs); // cap at ~60 fps
            }
        }
        catch { /* Verbindung fehlgeschlagen → Exit */ }
    }

    private static uint SampleHash(Bitmap bmp)
    {
        // Sample 64 evenly-distributed pixels — fast change detection, O(1)
        uint h = 2166136261u;
        int w = bmp.Width, ht = bmp.Height;
        int stepX = Math.Max(1, w / 8);
        int stepY = Math.Max(1, ht / 8);
        for (int y = 0; y < ht; y += stepY)
            for (int x = 0; x < w; x += stepX)
            {
                var c = bmp.GetPixel(x, y);
                h = (h ^ (uint)c.ToArgb()) * 16777619u;
            }
        return h;
    }
}
