using System.Collections.ObjectModel;
using AutoMapper;
using CommunityToolkit.Mvvm.ComponentModel;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
using DMS.Application.Interfaces.Database;
using DMS.WPF.Interfaces;
using DMS.WPF.ViewModels.Items;
namespace DMS.WPF.Services;
///
/// MQTT数据服务类,负责管理MQTT服务器相关的数据和操作。
///
public class MqttDataService : IMqttDataService
{
private readonly IMapper _mapper;
private readonly IAppDataStorageService _appDataStorageService;
private readonly IDataStorageService _dataStorageService;
private readonly IMqttAppService _mqttAppService;
///
/// MqttDataService类的构造函数。
///
/// AutoMapper 实例。
/// MQTT应用服务实例。
public MqttDataService(IMapper mapper, IAppDataStorageService appDataStorageService, IDataStorageService dataStorageService, IMqttAppService mqttAppService)
{
_mapper = mapper;
_appDataStorageService = appDataStorageService;
_dataStorageService = dataStorageService;
_mqttAppService = mqttAppService;
}
///
/// 加载所有MQTT服务器数据。
///
public async Task LoadMqttServers()
{
try
{
// 加载MQTT服务器数据
_dataStorageService.MqttServers = _mapper.Map>(_appDataStorageService.MqttServers.Values);
}
catch (Exception ex)
{
// 记录异常或处理错误
Console.WriteLine($"加载MQTT服务器数据时发生错误: {ex.Message}");
}
}
///
/// 添加MQTT服务器。
///
public async Task AddMqttServer(MqttServerItemViewModel mqttServer)
{
var dto = _mapper.Map(mqttServer);
var id = await _mqttAppService.CreateMqttServerAsync(dto);
dto.Id = id;
var mqttServerItem = _mapper.Map(dto);
_dataStorageService.MqttServers.Add(mqttServerItem);
return mqttServerItem;
}
///
/// 更新MQTT服务器。
///
public async Task UpdateMqttServer(MqttServerItemViewModel mqttServer)
{
var dto = _mapper.Map(mqttServer);
await _mqttAppService.UpdateMqttServerAsync(dto);
return true;
}
///
/// 删除MQTT服务器。
///
public async Task DeleteMqttServer(MqttServerItemViewModel mqttServer)
{
await _mqttAppService.DeleteMqttServerAsync(mqttServer.Id);
_dataStorageService.MqttServers.Remove(mqttServer);
return true;
}
}