using System;
using System.IO;
using System.Linq;
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.File.Application.Extension
{
    public static class SwaggerExtension
    {
        public static void AddFileSwaggerDoc(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 InclusionFileDoc(this ApiDescription apiDescription, string docName)
        {
            var assembly = apiDescription.ActionDescriptor.AsControllerActionDescriptor()
                .ControllerTypeInfo.Assembly;
            switch (docName)
            {
                case "文件":
                    return assembly == typeof(FileApplicationModule).Assembly;
            }
            return false;
        }

        public static void UseFileSwaggerUi(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);

        }
    }
}