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 ThingOperationHandler : IMqttMessageHandler
    {
        AirportMaintenanceApp _app;
        private readonly ICacheContext _cache;
        public ThingOperationHandler(AirportMaintenanceApp app, ICacheContext cache)
        {
            _app = app;
            _cache = cache;
        }
        public bool CanHandle(string topic)
        {
            return topic.Contains("/control-operation");
        }
        public async Task HandleAsync(string topic, string payload)
        {
            var root = JsonNode.Parse(payload)?.AsObject();

            var dataNode = root?["Data"];
            string dataJson = string.Empty;
            if (dataNode != null)
            {
                dataJson = System.Text.Json.JsonSerializer.Serialize(
                    dataNode,
                    new System.Text.Json.JsonSerializerOptions
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    });
            }

            await _app.AddOperationLog(new LasaControlOperation
            {
                Id = Guid.NewGuid().ToString(),
                DeviceSn = root?["DeviceSn"]?.ToString() ?? "",
                TaskId = root?["TaskId"]?.ToString() ?? "",
                CreateTime = DateTime.Now,
                CreateId = long.Parse(root?["CreateId"]?.ToString() ?? "0"),
                Data = dataJson
            });
        }
    }
}
