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);

            // Capture-Region bestimmen: 0 = alle Screens, 1-N = spezifischer Screen
            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;
            }

            while (tcp.Connected)
            {
                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));

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

                    // 4-Byte Länge (LE) + JPEG-Daten
                    stream.Write(BitConverter.GetBytes(jpeg.Length));
                    stream.Write(jpeg);
                    stream.Flush();
                }
                catch { break; }

                Thread.Sleep(150); // ~6-7 fps
            }
        }
        catch { /* Verbindung fehlgeschlagen → Exit */ }
    }
}
