using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BuechermarktClient
{
   /// <summary>
   /// Interaktionslogik für GetConnection.xaml
   /// </summary>
   public partial class GetConnection : Window
   {
      public const string ServerIdentifier = "BUECHERMARKTCLIENT00018946";

      public GetConnection()
      {
         InitializeComponent();
         Loaded += (sender, e) =>
         {
            ListenForServer();
         };
      }

      

      private UdpClient UdpClient;

      public void ListenForServer()
      {
         UdpClient = new UdpClient(3000);
         UdpClient.BeginReceive(Recevie, new object());
      }

      public void Recevie(IAsyncResult ar)
      {
         var ip = new IPEndPoint(IPAddress.Any, 15000);
         var bytes = UdpClient.EndReceive(ar, ref ip);
         string message = Encoding.ASCII.GetString(bytes);
         if(message == ServerIdentifier)
         {
            MainWindow.MongoHost = ip.Address.ToString();
            Dispatcher.BeginInvoke(new Action(delegate () {
               Close();
            }));
            //Success
         } else
         {
            //Retry
            ListenForServer();
         }
      }
   }
}
