using SampleServiceNamespace;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace SelfHostConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            using (ServiceHost host = new ServiceHost(typeof(SampleService)))
            {

                ServiceDebugBehavior debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();

                // if not found - add behavior with setting turned on 
                if (debug == null)
                {
                    host.Description.Behaviors.Add(new ServiceDebugBehavior() {IncludeExceptionDetailInFaults = true});
                }
                else
                {
                    // make sure setting is turned ON
                    if (!debug.IncludeExceptionDetailInFaults)
                    {
                        debug.IncludeExceptionDetailInFaults = true;
                    }
                }

                host.Open();

                Console.WriteLine("Service up and running at:");
                foreach (var ea in host.Description.Endpoints)
                {
                    Console.WriteLine(ea.Address);
                }

                Console.ReadLine();
                host.Close();
            }
        }

        private static readonly List<String> AccuZipAssemblyNames = new List<String> {"AccuAddress.dll", "log4net.dll"};

        private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(Object sender, ResolveEventArgs args)
        {
            String assemblyName = args.Name.Split(new[] {','}, 2)[0] + ".dll";
            String archSpecificPath =
                System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, assemblyName);
            Boolean fileExists = System.IO.File.Exists(archSpecificPath);
            Boolean nameIsValid = AccuZipAssemblyNames.Contains(assemblyName);
            Assembly assembly = null;
            if (fileExists && nameIsValid)
            {
                assembly = Assembly.LoadFile(archSpecificPath);
            }

            return assembly;
        }
    }
}
