using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using detect.device;
using detect.device.Utils;
using detect.gui.Models.Entities;
using detect.gui.Services.Detect;
using Serilog;
using Splat;

namespace detect.gui.Services;

public class DeviceClientService
{
    private readonly IDictionary<long, IDeviceClient> _deviceClients = new Dictionary<long, IDeviceClient>();

    public DeviceClientService()
    {
        ConnectAllDevices();
        Log.Warning("DeviceClientService Initializing...");
    }

    /// <summary>
    /// 连接所有设备
    /// </summary>
    public void ConnectAllDevices()
    {
        var eventService = Locator.Current.GetService<DetectDeviceService>()!;
        var devices = eventService.ListAll().Result!;
        if (devices.Any())
        {
            devices.ForEach(device =>
            {
                ConnectDevice(device);
            });
        }
    }
    
    /// <summary>
    /// 根据设备id获取连接客户端
    /// </summary>
    /// <param name="deviceId"></param>
    /// <returns></returns>
    public IDeviceClient? GetDeviceClient(long deviceId)
    {
        _deviceClients.TryGetValue(deviceId, out var deviceClient);
        return deviceClient;
    }
    
    /// <summary>
    /// 连接云台设备
    /// </summary>
    /// <param name="device"></param>
    /// <returns></returns>
    public IDeviceClient? ConnectDevice(DeviceEntity device)
    {
        // if (string.IsNullOrEmpty(device.DeviceIp) || string.IsNullOrEmpty(device.DevicePort))
        // {
        //     Log.Warning("设备【{Name}】没有配置ip和端口，不连接", device.Name);
        //     return null;
        // }
        _deviceClients.TryGetValue(device.Id!.Value, out var deviceClient);
        // if (deviceClient == null)
        // {
        //     deviceClient = new DeviceClientSocket(device.DeviceIp!, Convert.ToInt32(device.DevicePort));
        //     deviceClient.ConnectAsync();
        //     _deviceClients.Add(device.Id!.Value, deviceClient);
        // }
        // else
        // {
        //     if (!deviceClient.Connected())
        //     {
        //         deviceClient.ConnectAsync();
        //     }
        // }
        //
        // deviceClient.DeviceEvent += DeviceClientOnDeviceEvent;
        //
        return deviceClient;
    }

    private void DeviceClientOnDeviceEvent(object? sender, DeviceEvent e)
    {
        // var deviceService = Locator.Current.GetService<VapDeviceService>()!;
        // var eventService = Locator.Current.GetService<VapEventService>()!;
        // var constantService = Locator.Current.GetService<VapConstantService>()!;
        // var deviceClient = sender as DeviceClientSocket;
        // var device = deviceService.ListByDeviceIp(deviceClient!.Address).Result!;
        // var eventEntity = new EventEntity
        // {
        //     RegionId = device.RegionId,
        //     DeviceId = device.Id,
        //     Code = e.Result["alarmType"] as string,
        //     AlarmLevel = "INFO",
        //     ImageUrl = $"http://{device.DeviceIp}:8000/{e.Result["image"] as string}",
        //     EventTime = DateTime.Parse((e.Result["datetime"] as string)!)
        // };
        // if (eventEntity.ImageUrl.StartsWith("http"))
        // {
        //     var constant = constantService.ListOne(code: VapConstantService.EVENT_DATA_SAVE_PATH).Result;
        //     var savePath = Path.Join(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments),
        //         "aivap/event");
        //     if (constant != null)
        //     {
        //         savePath = constant.Value;
        //     }
        //     savePath = Path.Join(savePath, eventEntity.DeviceId.ToString());
        //     if (!Directory.Exists(savePath))
        //     {
        //         Directory.CreateDirectory(savePath!);
        //     }
        //     var filename = eventEntity.ImageUrl.Split("/").Last();
        //     var filePath = Path.Join(savePath!, filename);
        //     try
        //     {
        //         FileUtil.DownloadFileAsync(eventEntity.ImageUrl, filePath).GetAwaiter().GetResult();
        //         Log.Information("事件图片下载完成：{path}", filePath);
        //         eventEntity.ImageUrl = new FileInfo(filePath).FullName;
        //     }
        //     catch (Exception ex)
        //     {
        //         Log.Error(ex, "事件图片下载完成：{Error}", ex.Message);
        //     }
        // }
        // eventService.AddData(eventEntity);
    }
}