using System.Net;
using System.Net.Sockets;
using System.Text;
using Interfaces;

namespace UdpNotifier
{
    public class UdpNotifierProvider:INotifierProvider
    {
        private ILoggerService _logger;

        public UdpNotifierProvider(ILoggerService logger)
        {
            _logger = logger;
        }

        public string GetDisplayName()
        {
            return "UDP Notifier";
        }

        public PluginDetails GetPluginDetails()
        {
            return new PluginDetails("UdpNotifier", "Chris Watts", "UDP Notification engine", "1.0.0.0");
        }

        public void NotifyRaceStarted(NotificationEventArgs args)
        {
            _logger.Trace("Sending RaceStartedNotification");
            Send();
        }

        public void NotifyRaceStarting(NotificationEventArgs args)
        {
            Send();
        }

        public void NotifyRaceLapEvent(NotificationEventArgs args, Pilot pilot)
        {
            Send();
        }

        public void NotifyRaceWinner(NotificationEventArgs args, Pilot pilot)
        {
            Send();
        }

        public void NotifyRaceFinished(NotificationEventArgs args)
        {
            Send();
        }

        private void Send()
        {
            var endpoint = new IPEndPoint(IPAddress.Parse(GetLocalIp()), 0);
            var client = new UdpClient(endpoint);
            var ip = new IPEndPoint(IPAddress.Broadcast, 15000);
            var bytes = Encoding.ASCII.GetBytes("Foo");
            client.Send(bytes, bytes.Length, ip);
            client.Close();
        }

        private string GetLocalIp()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return "0.0.0.0";
        }
    }
}