using System;
using System.IO;
using System.Reflection;
using Abp.AspNetCore.Mvc.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace YGNT.QuestionLibrary.Extension
{
    public static class SwaggerExtension
    {
        public static void AddQuestionLibrarySwaggerDoc(this SwaggerGenOptions options, string systemName)
        {
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            FileInfo fileInfo = new FileInfo(xmlFile);
            options.SwaggerDoc("题库", new OpenApiInfo()
            {
                Title = $"{systemName}题库接口文档",
                Version = "v1",
                Description = $"基于.NET Core 3.1 的接口文档（{fileInfo.LastWriteTime:yyyy-MM-dd HH:mm}）"
            });
            SetXmlComments(xmlFile, options);

        }

        public static bool InclusionQuestionLibraryDoc(this ApiDescription apiDescription, string docName)
        {
            var assembly = apiDescription.ActionDescriptor.AsControllerActionDescriptor()
                .ControllerTypeInfo.Assembly;
            switch (docName)
            {
                case "题库":
                    return assembly == typeof(QuestionLibraryApplicationModule).Assembly;
            }
            return false;
        }

        public static void UseQuestionLibrarySwaggerUi(this SwaggerUIOptions options, string systemName)
        {
            options.SwaggerEndpoint($"/swagger/题库/swagger.json", $"{systemName} API 题库");
        }

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

        }
    }
}