using DD.Persistence.Client.Clients.Interfaces; using DD.Persistence.Models; using DD.Persistence.Models.Common; using System.Text.Json; namespace DD.Persistence.Client.Clients.Mapping; internal class SetpointMappingClient(ISetpointClient setpointClient, Dictionary mappingConfigs) : ISetpointMappingClient { public async Task Add(Guid setpointKey, object newValue, CancellationToken token) => await setpointClient.Add(setpointKey, newValue, token); public void Dispose() { setpointClient.Dispose(); } public async Task> GetCurrent(IEnumerable setpointKeys, CancellationToken token) => (await setpointClient.GetCurrent(setpointKeys, token)) .Select(x => new SetpointValueDto { Key = x.Key, Value = DeserializeValue(x.Key, (JsonElement)x.Value) }); public async Task> GetCurrentDictionary(IEnumerable setpointConfigs, CancellationToken token) { return (await setpointClient.GetCurrent(setpointConfigs, token)) .ToDictionary(x => x.Key, x => DeserializeValue(x.Key, (JsonElement)x.Value)); } public async Task GetDatesRangeAsync(CancellationToken token) => await setpointClient.GetDatesRangeAsync(token); public async Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token) { var result = await setpointClient.GetHistory(setpointKeys, historyMoment, token); foreach (var dto in result) dto.Value = DeserializeValue(dto.Key, (JsonElement)dto.Value); return result; } public async Task>> GetLog(IEnumerable setpointKeys, CancellationToken token) { var result = await setpointClient.GetLog(setpointKeys, token); foreach (var item in result) DeserializeList(result[item.Key]); return result; } public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) { var res = await setpointClient.GetPart(dateBegin, take, token); DeserializeList(res); return res; } private object DeserializeValue(Guid key, JsonElement value) { if (mappingConfigs.TryGetValue(key, out var type)) return value.Deserialize(type)!; return value; } private void DeserializeList(IEnumerable? result) { foreach (var log in result) log.Value = DeserializeValue(log.Key, (JsonElement)log.Value); } }