using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace GxPress.Api.ServiceExtensions
{
    public static class SwaggerExtension
    {
        /// <summary>
        /// 添加swagger
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSwashbuckle(this IServiceCollection services)
        {
            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "GxPress API",
                    Version = "v1",
                    Description = "广西出版集团"
                });
                x.CustomSchemaIds(n => n.FullName);
                x.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "GxPress.Api.xml"), true);
                x.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "GxPress.Request.xml"));
                x.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "GxPress.Result.xml"));
                x.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "GxPress.Entity.xml"));

                //添加token认证
                x.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                        },
                        new string[]{}
                    }
                });
                x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token} (注意两者之间是一个空格)",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置
                    Type = SecuritySchemeType.ApiKey
                });
            });

            return services;
        }

        /// <summary>
        /// 使用swagger
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseSwashbuckle(this IApplicationBuilder app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "GxPress API V1"); });
            app.UseReDoc(c =>
            {
                c.SpecUrl("/swagger/v1/swagger.json");
                c.RoutePrefix = "docs";
                c.DocumentTitle = "广西出版集团";
                c.RequiredPropsFirst();
            });

            return app;
        }

    }
}