using Infrastructure.CloudSdk.mqttmessagecenter;
using NPOI.SS.Formula.Functions;
using NuGet.Packaging;
using OpenAuth.App.ServiceApp;
using System.Security.Cryptography;

namespace OpenAuth.WebApi.Model.mqtt
{
    public class MqttHostedService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly MqttMessageCenter _mqttCenter;
        private readonly AirportMaintenanceApp _app;


        public MqttHostedService(IServiceProvider serviceProvider, MqttMessageCenter mqttCenter, AirportMaintenanceApp app)
        {
            _serviceProvider = serviceProvider;
            _mqttCenter = mqttCenter;
            _app = app;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using var scope = _serviceProvider.CreateScope();
            var handlers = scope.ServiceProvider.GetServices<IMqttMessageHandler>();
            // 创建配置构建器
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile(
                    $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json",
                    optional: true)
                .AddEnvironmentVariables();
            // 构建配置
            var configuration = builder.Build();
            // 读取连接字符串
            var serverIp = configuration["MQTT:Server"];
            var port = configuration["MQTT:Port"];
            var username = configuration["MQTT:UserName"];
            var password = configuration["MQTT:Password"];

            await _mqttCenter.InitializeAsync(
                handlers,
                server: serverIp,
                port: int.Parse(port),
                clientId: Guid.NewGuid().ToString(),
                username: username,
                password: password
            );
            //查询网关，订阅主题 
            var topics = new List<string>();
            var gatewayList = await _app.GetGatewaysnList();

            foreach (var gateway in gatewayList)
            {
                topics.AddRange(new[]
                {
                    $"thing/product/{gateway}/osd",
                    $"thing/product/{gateway}/events",
                    $"thing/product/{gateway}/requests",
                    $"thing/product/{gateway}/services_reply",
                    //$"thing/product/{gateway}/drc/up",
                    //$"thing/product/{gateway}/drc/down",
                    $"sys/product/{gateway}/status"
                });
            }
            var snList = await _app.GetUavSn();

            foreach (var sn in snList)
            {
                topics.AddRange(new[]
                {
                  //  $"thing/product/1581F8HGX254V00A0BUY/osd",
                    $"thing/product/{sn}/osd"
                });
            }
            await _mqttCenter.ConnectAndSubscribeAsync(topics.ToArray());
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
}
