using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using detect.gui.Api.System;
using detect.gui.Converters;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using xwd.utils;

namespace detect.gui.Api;

public class ApiService
{
    private static ApiService? _instance;

    public static ApiService Instance()
    {
        return _instance ??= new ApiService();
    }

    private WebApplication? _webApp = null;

    public void StartService()
    {
        if (_webApp != null) return;
        var appBuilder = WebApplication.CreateBuilder();
        appBuilder.Services.AddRouting();
        appBuilder.Services.AddLogging();
        // 添加 CORS 服务
        appBuilder.Services.AddCors(options =>
        {
            options.AddPolicy("AllowAll", builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
            });
        });
        // json
        appBuilder.Services.Configure<JsonOptions>(options =>
        {
            options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); // 可选：支持枚举为字符串
            options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; // 使用驼峰命名法
            options.SerializerOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss")); // 设置日期时间格式
        });
        _webApp = appBuilder.Build();
        // 使用 CORS 中间件
        _webApp.UseCors("AllowAll");

        // api
        _ = new UserApi(_webApp);
        _ = new AuthorityApi(_webApp);
        _ = new DetectTaskApi(_webApp);
        _ = new DetectTaskLogApi(_webApp);
        _ = new DetectTaskProgressApi(_webApp);
        _ = new DeviceApi(_webApp);
        _ = new LogApi(_webApp);

        Task.Run(() => { _webApp.RunAsync(AppSettingsManager.Manager().GetString("ApiUrl")); });
        Log.Information("Web Application is started!");
    }

    public async void StopService()
    {
        if (_webApp == null) return;
        await _webApp.StopAsync();
        _webApp = null;
        Log.Information("Web Application is stopped!");
    }
}