using Infrastructure.CloudSdk.mqttmessagecenter;
using NuGet.Packaging;
using OpenAuth.App.ServiceApp;

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>();

            await _mqttCenter.InitializeAsync(
                handlers,
                server: "175.27.168.120",
                port: 6011,
                clientId: "mqtt_client_1582",
                username: "sdhc",
                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",
                    $"thing/product/{gateway}/state"
                });
            }
            await _mqttCenter.ConnectAndSubscribeAsync(topics.ToArray());
        }

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