using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace isnd.tests
{

    [CollectionDefinition("Web server collection")]


    public class WebServerFixture : IDisposable
    {
        public IWebHost Host { get; private set;}
        public List<string> Addresses { get; private set; } = new List<string>();

        public WebServerFixture()
        {
            SetupHost();
        }

        public void Dispose()
        {
            Host.StopAsync().Wait();
            Host.Dispose();
        }

        public void SetupHost()
        {
            var webhostBuilder = new WebHostBuilder()
               .UseKestrel()
               .UseIISIntegration()
           //    .UseContentRoot("../../../../../src/isnd")
               .UseStartup(typeof(Startup))
               .ConfigureAppConfiguration((builderContext, config) =>
               {
                   config.AddJsonFile("appsettings.json", false);
                   config.AddJsonFile("appsettings.Development.json", false);
               });

            Host = webhostBuilder.Build();

            Host.Start(); //Starts listening on the configured addresses.
            PrintAddresses(Host.Services);
        }

        void PrintAddresses(IServiceProvider services)
        {
            Addresses.Clear();
            Console.WriteLine("Checking addresses...");
            var server = services.GetRequiredService<IServer>();
            var addressFeature = server.Features.Get<IServerAddressesFeature>();
            foreach (var address in addressFeature.Addresses)
            {
                Console.WriteLine("Listing on address: " + address);
                Addresses.Add(address);
            }
        }
    }
}