using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BuechermarktServer
{
   class Program
   {
      public const string ServerIdentifier = "BUECHERMARKTCLIENT00018946";
      public const string RelativeDbPath = ".\\db";

      static void Main(string[] args)
      {
         if (!Directory.Exists(RelativeDbPath))
         {
            Directory.CreateDirectory(RelativeDbPath);
         }
         var process = new Process();

         process.StartInfo.FileName = ".\\mongod.exe";
         process.StartInfo.WorkingDirectory = Process.GetCurrentProcess().StartInfo.WorkingDirectory;
         process.StartInfo.Arguments = "--dbpath " + RelativeDbPath;
         process.StartInfo.RedirectStandardOutput = true;
         process.StartInfo.RedirectStandardError = true;
         process.StartInfo.UseShellExecute = false;
         process.StartInfo.CreateNoWindow = true;
         process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
         process.OutputDataReceived += Process_OutputDataReceived;
         process.ErrorDataReceived += Process_OutputDataReceived;
         var s = process.Start();
         ChildProcessTracker.AddProcess(process);
         process.BeginErrorReadLine();
         process.BeginOutputReadLine();
         while (!process.WaitForExit(100))
         {
            Broadcast();
         }
         Thread.Sleep(10000);
      }

      private static void P_Exited(object sender, EventArgs e)
      {
         throw new NotImplementedException();
      }

      private static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
      {
         Console.WriteLine(e.Data);
      }

      static void Broadcast()
      {
         UdpClient client = new UdpClient();
         IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 3000);
         byte[] bytes = Encoding.ASCII.GetBytes(ServerIdentifier);
         try
         {
            client.Send(bytes, bytes.Length, ip);
         } catch (Exception ex)
         {
            Console.WriteLine(ex);
         }
      }
   }
}
