// Created with MonoDevelop
//
//    Copyright (C) 2009 Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using System.Diagnostics;
using Hiperscan.Common.SearchIpAddress;

namespace Hiperscan.MDnsSearch
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Running Mdns-service...");


                SearchIPAdr.Parameter parameter = new SearchIPAdr.Parameter(args);
                SearchIPAdr addresses = Program.SearchApoIdent(parameter);

                if (addresses.HasAdresses == false)
                    throw new Exception("No addresses found.");

                addresses.WriteFullAddresses();
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error while running Mdns-service: {0}", ex);
                Environment.Exit(1);
            }

            Environment.Exit(0);
        }

        private static SearchIPAdr SearchApoIdent(SearchIPAdr.Parameter parameter)
        {
            Stopwatch stop_watch = new Stopwatch();
            stop_watch.Start();

            SearchIPAdr addresses = new SearchIPAdr();

            try
            {
                addresses.Run(parameter);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception " + ex.Message);
            }
            finally
            {
                stop_watch.Stop();
                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stop_watch.Elapsed;

                // Format and display the TimeSpan value.
                string elapsed_time = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                    ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

                Debug.WriteLine("MDnsSearch duration: {0}",elapsed_time);
            }

            return addresses;
        }
    }
}
