using System;
using System.IO;
using System.Reflection;
using Abp.AspNetCore.Mvc.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using YGNT.Exam.Controllers;
using YGNT.File.Application;
using YGNT.File.Application.Extension;
using YGNT.QuestionLibrary;
using YGNT.QuestionLibrary.Extension;

namespace YGNT.Exam.Web.Host.Extension
{
    public static class SwaggerSetup
    {
        /// <summary>
        /// 启用Swagger配置
        /// </summary>
        /// <param name="services"></param>
        public static void AddSwaggerGenSetup(this IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                FileInfo fileInfo = new FileInfo(xmlFile);

                options.SwaggerDoc("系统管理", new OpenApiInfo()
                {
                    Title = "考试系统管理接口文档",
                    Version = "v1",
                    Description = $"基于.NET Core 3.1 的接口文档（{fileInfo.LastWriteTime:yyyy-MM-dd HH:mm}）"
                });


                options.AddFileSwaggerDoc("考试系统");
                options.AddQuestionLibrarySwaggerDoc("考试系统");

                options.DocInclusionPredicate((docName, description) =>
                {
                    var assembly = description.ActionDescriptor.AsControllerActionDescriptor()
                        .ControllerTypeInfo.Assembly;
                    if (description.InclusionFileDoc(docName))
                        return true;
                    if (description.InclusionQuestionLibraryDoc(docName))
                        return true;

                    switch (docName)
                    {
                        case "系统管理":
                            return assembly == typeof(ExamApplicationModule).Assembly || assembly == typeof(TokenAuthController).Assembly;
                    }
                    return false;
                });

                // Define the BearerAuth scheme that's in use
                SetAuthorization(options);
                SetXmlComments(xmlFile, options);
                options.DocumentFilter<SwaggerEnumFilter>();
            });
        }

        public static void UseSwaggerUiSetup(this IApplicationBuilder app)
        {
            app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint($"/swagger/系统管理/swagger.json", $"YGNT.Exam API 系统管理");

                options.UseFileSwaggerUi("YGNT.Exam");
                options.UseQuestionLibrarySwaggerUi("YGNT.Exam");

                options.IndexStream = () =>
                {
                    var stream = Assembly.GetExecutingAssembly()
                        .GetManifestResourceStream("YGNT.Exam.Web.Host.wwwroot.swagger.ui.index.html");
                    return stream;
                };
                options.DisplayRequestDuration();
            });
        }


        private static void SetAuthorization(SwaggerGenOptions options)
        {
            options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });
            options.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "bearerAuth"
                        }
                    },
                    new string[] { }
                }
            });
        }

        private static void SetXmlComments(string xmlFile, SwaggerGenOptions options)
        {
            // 为 Swagger 设置xml文档注释路径
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            options.IncludeXmlComments(xmlPath, true);

            xmlPath = xmlPath.Replace(Path.GetFileName(xmlPath), "YGNT.Exam.Application.xml");
            options.IncludeXmlComments(xmlPath);


        }
    }
}