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

namespace Inspectron.HawkEye
{
    public class UDTServer
    {
        private readonly IImageSource _imageSource;
        UdtSharp.UdtSocket _server;
        public UDTServer(IImageSource imageSource)
        {
            _imageSource = imageSource;

            _server = new UdtSharp.UdtSocket(AddressFamily.InterNetwork, SocketType.Stream);

            _server.Bind(new IPEndPoint(IPAddress.Any, 27001));

            _server.Listen(1);
        }

        
        public void Receive()
        {
            while (true)
            {
                var socket=_server.Accept();
                byte[] buffer = new byte[10];
                while (socket.IsConnected())
                {

                    socket.Receive(buffer, 0, 10);

                    switch ((ERequestType) buffer[0])
                    {
                        case ERequestType.Trigger:
                        {
                            var image = _imageSource.GetImage();
                                int sent = 0;
                            while (sent < image.Length)
                            {
                                sent += socket.Send(image, sent, image.Length - sent);
                            }
                                
                            
                        }
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }
        }
    }
}