using Infrastructure.Cache;
using Infrastructure.CloudSdk.mqttmessagecenter;
using OpenAuth.App.ServiceApp;
using OpenAuth.Repository.Domain;
using System.Text.Json.Nodes;

namespace OpenAuth.WebApi.Model.mqtt
{
    public class ThingOsdHandler : IMqttMessageHandler
    {
        private readonly ILogger<ThingRequestHandler> _logger;
        AirportMaintenanceApp _app;
        private readonly ICacheContext _cache;
        public ThingOsdHandler(ILogger<ThingRequestHandler> logger, AirportMaintenanceApp app, ICacheContext cache)
        {
            _logger = logger;
            _app = app;
            _cache = cache;
        }

        public bool CanHandle(string topic)
        {
            return topic.Contains("/osd");
        }

        public Task HandleAsync(string topic, string payload)
        {
            //_logger.LogError($"[osd] Topic={topic}, Payload={payload}");
            //Console.WriteLine($"[osd] Topic={topic}, Payload={payload}");
            var root = JsonNode.Parse(payload)?.AsObject();
            _app.AddLog(new LasaLog
            {
                Id = Guid.NewGuid().ToString(),
                Topic = topic,
                Method = root["method"]?.ToString() ?? "",
                CreateTime = DateTime.Now,
                Data = payload
            });
            var sub_device = root["data"]?["sub_device"]?.ToString() ?? "";
            if (!string.IsNullOrEmpty(sub_device))
            { 
                var data = new
                {
                    device_sn = root["data"]?["sub_device"]?["device_sn"]?.ToString() ?? "",
                    device_online_status = root["data"]?["sub_device"]?["device_online_status"]?.ToString() ?? "",
                    mode_code = root["data"]?["mode_code"]?.ToString() ?? "",
                };
                var a = _cache.Set("DeviceState", data, DateTime.Now.AddMinutes(1));
            } 
            // 自定义处理逻辑
            return Task.CompletedTask;
        }
    }
}
