using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Inspectron.HawkEye.Protocol.Discovery
{
    public class DiscoveryServer
    {
        private UdpClient _server;
        private byte[] _name;

        public DiscoveryServer(int port,string name=null)
        {
            _server = new UdpClient(port);
            
            if(name==null)
            { _name = Encoding.UTF8.GetBytes( NetworkInterface
                .GetAllNetworkInterfaces()
                .Where(nic => nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                .Select(nic => nic.GetPhysicalAddress().ToString())
                .FirstOrDefault());

            }
            else
            {
                _name = Encoding.UTF8.GetBytes(name);
            }
            
        }

        public void Start()
        {
            Thread th = new Thread(DiscoveryLoop);
            th.Start();
        }
        private void DiscoveryLoop()
        {
            while (true)
            {
                var clientEp = new IPEndPoint(IPAddress.Any, 0);
                var clientRequestData = _server.Receive(ref clientEp);
                var clientRequest = Encoding.ASCII.GetString(clientRequestData);

                Console.WriteLine("Recived {0} from {1}, sending response", clientRequest, clientEp.Address.ToString());
                _server.Send(_name, _name.Length, clientEp);
                _server.Send(_name, _name.Length, clientEp);
                _server.Send(_name, _name.Length, clientEp);
            }
        }
    }
}