using Infrastructure;
using Infrastructure.CloudSdk.mqttmessagecenter;
using Microsoft.AspNetCore.Mvc;
using NetTopologySuite.Mathematics;
using OpenAuth.App;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp;
using OpenAuth.Repository.Domain;
using OpenAuth.WebApi.Model.mqtt.ModelResponse;
using System.Collections.Generic;
using System.Text.Json;

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

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

        public Task HandleAsync(string topic, string payload)
        {
            //_logger.LogError($"[osd] Topic={topic}, Payload={payload}");
            //Console.WriteLine($"[osd] Topic={topic}, Payload={payload}");
            if (payload.Contains("hms"))//健康告警
            {
                var jsondata = JsonSerializer.Deserialize<HmsMessage>(payload);

                var path = Path.Combine(AppContext.BaseDirectory, "hms.json");
                string getway = topic.Split('/')[2];
                var parser = new HmsAlarmParser(path, getway);
                List<LasaManageDeviceHms> alarmMessages = null;
                if (jsondata.data != null && jsondata.data.list?.Count > 0)
                {
                    alarmMessages = parser.ParseAlarmMessages(payload);
                } 
                _app.AddManageDeviceHms(alarmMessages ?? new List<LasaManageDeviceHms>());

            } 
            return Task.CompletedTask;
        }
    }
}
