using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ServiceModel.Discovery;
using GeometryServiceClients.DiscoveryEnabled.GeometryServiceReference;

namespace GeometryServiceClients.DiscoveryEnabled
{
    class Program
    {
        private static EndpointDiscoveryMetadata discoveredService = null;

        static void Main(string[] args)
        {
            bool keepLooking = true;
            Console.WriteLine("Discovery client is starting");

            while (keepLooking)
            {
                keepLooking = TryToFindService();
                if (keepLooking)
                {
                    Console.WriteLine("Service not found, keep looking? (y/n)");
                    keepLooking = ReadUserInput();
                    if (keepLooking)
                    {
                        Console.WriteLine("\nSleeping for some time");
                        System.Threading.Thread.Sleep(5000);
                    }
                }
                else
                {
                    Console.WriteLine("Service discovered");
                    CallService();
                }
            }

            Console.WriteLine("Discovery client did his job. Now shuting down.");
            Console.ReadLine();
        }

        private static bool TryToFindService()
        {
            bool serviceNotFound = true;
            Console.WriteLine("Trying to find service");
            DiscoveryClient discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
            FindResponse geometryServices = discoveryClient.Find(new FindCriteria(typeof(GeometryServiceReference.IGeometryService)));
            discoveryClient.Close();

            if (geometryServices.Endpoints.Count > 0)
            {
                discoveredService = geometryServices.Endpoints[0];
                serviceNotFound = false;
            }

            return serviceNotFound;
        }

        private static void CallService()
        {
            GeometryServiceClient client = new GeometryServiceClient();
            client.Endpoint.Address = discoveredService.Address;
            Console.WriteLine("GetRectangleArea with 2 and 3 result {0}", client.GetRectangleArea(new GeometryServiceReference.Rectangle() { A = 2, B = 3 }));
        }

        private static bool ReadUserInput()
        {
            ConsoleKeyInfo cki = Console.ReadKey();
            if (cki.KeyChar == 'y' || cki.KeyChar == 'Y')
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
