using CloudGaming.AppConfigModel;
using CloudGaming.Code.AppExtend;
using CloudGaming.Code.DataAccess.MultiTenantUtil;
using CloudGaming.Code.Extend;
using CloudGaming.Code.Filter;
using CloudGaming.Code.Game;
using CloudGaming.Code.Monitor;
using CloudGaming.DtoModel;
using CloudGaming.GameModel.Db.Db_Ext;
using CloudGaming.GameModel.Db.Db_Game;
using CloudGaming.Model.DbSqlServer.Db_User;

using HuanMeng.DotNetCore.CustomExtension;
using HuanMeng.DotNetCore.MiddlewareExtend;
using HuanMeng.DotNetCore.SwaggerUtile;

using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.OpenApi.Models;

using Newtonsoft.Json.Serialization;

using Serilog;

using System.Diagnostics;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor(); //添加httpContext注入访问
#region 日志
// Add services to the container.
builder.Host.UseSerilog((context, services, configuration) => configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext());

builder.Services.AddSingleton(typeof(ILogger<CloudGamingBase>), serviceProvider =>
{
    var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
    return loggerFactory.CreateLogger<CloudGamingBase>();
});
//
builder.Services.AddSingleton(typeof(ILogger<ExceptionMiddleware>), serviceProvider =>
{
    var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
    return loggerFactory.CreateLogger<ExceptionMiddleware>();
});
#endregion
#region  automap
var mapperDomain = AppDomain.CurrentDomain.GetAssemblies().Where(it => it.FullName.Contains("HuanMeng") || it.FullName.Contains("CloudGaming.")).ToList();
AddAssembly(mapperDomain, typeof(T_App_Config));
AddAssembly(mapperDomain,typeof(AppConfig));
AddAssembly(mapperDomain, typeof(AppConfigCache));
AddAssembly(mapperDomain, typeof(T_User));
builder.Services.AddAutoMapper(mapperDomain);
#endregion
#region 添加跨域
var _myAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCustomCors(_myAllowSpecificOrigins);
#endregion
builder.Services.AddHttpContextAccessor(); //添加httpContext注入访问
#region 返回数据解析  
//builder.Services.AddControllers();
builder.Services.AddControllers(options =>
{
})
    .AddNewtonsoftJson(options =>
    {
        // 配置 Newtonsoft.Json 选项
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // 忽略循环引用
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();// 首字母小写（驼峰样式）
        //options.SerializerSettings.ContractResolver = new LanguageContractResolver(builder.Services);
        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";// 时间格式化
        options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
    });
//CustomResultFilter
//builder.Services.AddSingleton<ObjectResultExecutor, CustomObjectResultExecutor>();

#endregion

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    string description = "";
    var filePath = Path.GetFullPath(".versionDescribe");
    if (File.Exists(filePath))
    {
        description = File.ReadAllText(filePath);
    }
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "蒸汽云游戏扩展", Version = "0.0.1", Description = description });
    foreach (var assemblies in AppDomain.CurrentDomain.GetAssemblies())
    {
        // 添加 XML 注释文件路径
        var xmlFile = $"{assemblies.GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        if (File.Exists(xmlPath))
        {
            c.IncludeXmlComments(xmlPath);
        }
    }
    c.ParameterFilter<LowercaseParameterFilter>();
    c.RequestBodyFilter<LowercaseRequestFilter>();
});
await builder.AddAppConfigClient();
//添加游戏服务
builder.AddPlayGameServer();
builder.AddMonitorConfig();
var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
app.UseSwagger();
app.UseSwaggerUI(c =>
{

    c.EnableDeepLinking();
    c.DefaultModelsExpandDepth(3);
    c.DefaultModelExpandDepth(3);
    c.EnableFilter("true");
    //c.RoutePrefix = string.Empty;
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "蒸汽云游戏扩展 API V1");
    // 使用自定义CSS
    c.InjectStylesheet("/custom.css");
});
//}
//使用跨域
app.UseCors(_myAllowSpecificOrigins);
app.UseAuthorization();
//数据库中间件
app.UseMultiTenantExt();
app.MapControllers();
app.UseMiddlewareAll();
#region 默认请求
#region 默认请求
app.UseAppRequest("ext");
#endregion
#endregion
app.Run();

void AddAssembly(List<Assembly> mapperDomain, Type type)
{
    
    if (type != null)
    {
        Assembly assembly = Assembly.GetAssembly(type);
        if (!mapperDomain.Any(it => it.FullName == assembly.FullName))
        {
            mapperDomain.Add(assembly);
        }
    }
}