using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;

namespace Performance.Api.Configurations
{
    public static class SwaggerConfig
    {
        public static void AddSwaggerConfiguration(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1.0", Title = "绩效API接口" });

                var xmlPath = new string[]
                {
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "Performance.Api.xml"),
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "Performance.DtoModels.xml"),
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "Performance.EntityModels.xml"),
                };

                foreach (var item in xmlPath)
                {
                    c.IncludeXmlComments(item, true);
                }

                //var xmlPathsss = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "Performance.Api.xml");
                //c.IncludeXmlComments(xmlPathsss, true);

                // Token绑定到ConfigureServices
                var security = new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference{ Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                        },
                        new List<string>()
                    }
                };
                c.AddSecurityRequirement(security);
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）",
                    Name = "Authorization",
                    In = ParameterLocation.Header
                });
            });

        }

        public static void UseSwaggerSetup(this IApplicationBuilder app, IConfiguration configuration)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint(configuration["Application:SwaggerEndpoint"], "v1.0");
                c.RoutePrefix = string.Empty;
            });
        }
    }
}
