using System;
namespace FastGithub
{
    /// 
    /// 中间件创建者扩展
    /// 
    public static class PipelineBuilderExtensions
    {
        /// 
        /// 中断执行中间件
        /// 
        /// 
        /// 
        /// 处理者
        /// 
        public static IPipelineBuilder Run(this IPipelineBuilder builder, InvokeDelegate handler)
        {
            return builder.Use(_ => handler);
        }
        /// 
        /// 条件中间件
        /// 
        /// 
        /// 
        /// 
        ///  
        /// 
        public static IPipelineBuilder When(this IPipelineBuilder builder, Func predicate, InvokeDelegate handler)
        {
            return builder.Use(next => async context =>
            {
                if (predicate.Invoke(context) == true)
                {
                    await handler.Invoke(context);
                }
                else
                {
                    await next(context);
                }
            });
        }
        /// 
        /// 条件中间件
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IPipelineBuilder When(this IPipelineBuilder builder, Func predicate, Action> configureAction)
        {
            return builder.Use(next => async context =>
            {
                if (predicate.Invoke(context) == true)
                {
                    var branchBuilder = builder.New();
                    configureAction(branchBuilder);
                    await branchBuilder.Build().Invoke(context);
                }
                else
                {
                    await next(context);
                }
            });
        } 
    }
}