using DFS.Core.Mvc;
using DFS.Core.Mvc.Filters;
using DFS.Core.Mvc.Jwt;
using DFS.Core.Utils;
using DFS.Core.Utily;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Fuel.PaymentServer.MicServer
{
    public static class WebAppliactionExtend
    {

        /// <summary>
        /// 添加服务注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="environmentName"></param>
        /// <returns></returns>
        public static IServiceCollection AddMicService(this IServiceCollection services, IWebHostEnvironment environmentName)
        {
            services.AddSingleton(new Appsettings(environmentName.ContentRootPath, environmentName.EnvironmentName));
            //services.AddJwtAuth();
            services.AddHealthChecks();
            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(ValidationActionFilter));
                options.Filters.Add(typeof(StandardResultFilter));
                options.Filters.Add(typeof(ServiceExceptionFilter));
            })
            .AddNewtonsoftJson(options =>//全局配置Json序列化处理
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }).AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter()));

            if (services.All(u => u.ServiceType != typeof(IHttpContextAccessor)))
            {
                services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            }
            return services;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="application"></param>
        /// <returns></returns>
        public static WebApplication UseDFSServer(this WebApplication application)
        {
            application.UseCors(p => p.AllowCredentials());
            return application;
        }
    }
}
