using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Inspectron.HawkEye.Protocol;
using UdtSharp;

namespace Inspectron.HawkEye
{
    public class UDTClient
    {
        UdtSharp.UdtSocket _client;

        public UDTClient():this(IPAddress.Loopback, 27001)
        {

        }
        public UDTClient(IPAddress address,int port)
        {
            
            _client = new UdtSharp.UdtSocket(AddressFamily.InterNetwork, SocketType.Stream);

            _client.Connect(new IPEndPoint(address, port));
        }

        public byte[] RequestImage()
        {
            var request = CreateTriggerRequest();
            _client.Send(request, 0, request.Length);
            
            byte[] buffer = new byte[2048 * 4 * 1000];

            int bytes = 0;
            while (bytes<buffer.Length)
            {
                bytes+=_client.Receive(buffer, bytes, buffer.Length- bytes);
            }
            
            
            
            Console.WriteLine($"Received {bytes} bytes");
            return buffer;
        }

        private byte[] CreateTriggerRequest()
        {
            byte[] result = new byte[5];
            using (MemoryStream stream = new MemoryStream(result))
            using (BinaryWriter writer = new BinaryWriter(stream))
            {
                writer.Write((byte)ERequestType.Trigger);
                writer.Flush();
            }

            return result;
        }
    }
}