using Infrastructure.Cache;
using OpenAuth.App.ServiceApp;
using OpenAuth.WebApi;
using Quartz;

namespace OpenAuth.App.BaseApp.Subscribe;

/// <summary>
/// 离线去订阅
/// </summary>
public class GlobalSubscribe : IJob
{
    public bool x = true; // 临时只执行一次
    public ManageApp manageApp;
    private MqttClientManager mqttManager;
    private RedisCacheContext redisCacheContext;

    public GlobalSubscribe(ManageApp manageApp, MqttClientManager mqttManager, ICacheContext redisCacheContext)
    {
        this.manageApp = manageApp;
        this.mqttManager = mqttManager;
        this.redisCacheContext = redisCacheContext as RedisCacheContext;
    }

    public Task Execute(IJobExecutionContext context)
    {
        Console.WriteLine($"running !{DateTime.Now}");
        /*var redisCacheContext = context.JobDetail.JobDataMap.Get("redisCacheContext") as RedisCacheContext;
        var serviceProvider = context.JobDetail.JobDataMap.Get("ServiceProvider") as IServiceProvider;
        var mqttManager = serviceProvider.GetService(typeof(MqttClientManager)) as MqttClientManager;
        if (manageApp == null)
        {
            manageApp = serviceProvider.GetService(typeof(ManageApp)) as ManageApp;
        }
        /*var ioc = IocManager.Instance;
        var redisCacheContext = IocManager.Instance.GetService<ICacheContext>();#1#
        // todo 如果无人机不在线，则订阅
        if (redisCacheContext == null) return Task.CompletedTask;*/
        var keys = redisCacheContext.GetAllKeys("online:*");
        foreach (var redisKey in keys)
        {
            var gatewaySn = redisKey.ToString()[7..];
            // todo 取得sn值 
            // todo 取得设备信息
            // todo 需要判断是不是要订阅，避免重复订阅
            if (mqttManager != null)
            {
                var droneDock = manageApp.GetDroneDockBySn(gatewaySn);
                /*if(droneDock)
            
                    /*mqttManager.SubscribeAsync($"thing/product/{gatewaySn}/services_reply",
                        async (args) => await TopicHandler.HandleTopic(gatewaySn, args.ApplicationMessage.Topic,
                            Encoding.UTF8.GetString(args.ApplicationMessage.Payload), serviceProvider));#1#
                    x = false;
                */
            }
            //statusSubscribe.subscribe(gateway);
            //stateSubscribe.subscribe(gateway, true);
            //osdSubscribe.subscribe(gateway, true);
            //servicesSubscribe.subscribe(gateway);
            //eventsSubscribe.subscribe(gateway, true);
            //requestsSubscribe.subscribe(gateway);
            //propertySetSubscribe.subscribe(gateway);
        }

        // todo
        return Task.CompletedTask;
    }
}