using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JiShe.CollectBus.Kafka.Test
{
    public class ConsoleApplicationBuilder: IApplicationBuilder
    {
        public IServiceProvider ApplicationServices { get; set; }
        public IDictionary<string, object> Properties { get; set; } = new Dictionary<string, object>();

        public IFeatureCollection ServerFeatures => throw new NotImplementedException();

        private readonly List<Func<RequestDelegate, RequestDelegate>> _middlewares = new();

        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _middlewares.Add(middleware);
            return this;
        }

        public RequestDelegate Build()
        {
            RequestDelegate app = context => Task.CompletedTask;
            foreach (var middleware in _middlewares)
            {
                app = middleware(app);
            }
            return app;
        }

        public IApplicationBuilder New()
        {
            return new ConsoleApplicationBuilder
            {
                ApplicationServices = this.ApplicationServices,
                Properties = new Dictionary<string, object>(this.Properties)
            };
        }
    }


    public static class HostBuilderExtensions
    {
        public static IHostBuilder ConfigureConsoleAppBuilder(
            this IHostBuilder hostBuilder,
            Action<IApplicationBuilder> configure)
        {
            hostBuilder.ConfigureServices((context, services) =>
            {
                // 注册 ConsoleApplicationBuilder 到 DI 容器
                services.AddSingleton<IApplicationBuilder>(provider =>
                {
                    var appBuilder = new ConsoleApplicationBuilder
                    {
                        ApplicationServices = provider // 注入服务提供者
                    };
                    configure(appBuilder); // 执行配置委托
                    return appBuilder;
                });
            });
            return hostBuilder;
        }
    }
}
