using FastGithub.FlowAnalyze;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
namespace FastGithub
{
    /// 
    /// ListenOptions扩展
    /// 
    public static class ListenOptionsExtensions
    {
        /// 
        /// 使用流量分析中间件
        /// 
        /// 
        /// 
        public static ListenOptions UseFlowAnalyze(this ListenOptions listen)
        {
            var flowAnalyzer = listen.ApplicationServices.GetRequiredService();
            listen.Use(next => async context =>
            {
                var oldTransport = context.Transport;
                try
                {
                    await using var loggingDuplexPipe = new FlowAnalyzeDuplexPipe(context.Transport, flowAnalyzer);
                    context.Transport = loggingDuplexPipe;
                    await next(context);
                }
                finally
                {
                    context.Transport = oldTransport;
                }
            });
            return listen;
        }
    }
}