using DD.Persistence.Database.Entity; using DD.Persistence.Models; using DD.Persistence.Models.Common; using DD.Persistence.Repositories; using Mapster; using Microsoft.EntityFrameworkCore; using System.Text.Json; namespace DD.Persistence.Repository.Repositories { public class SetpointRepository : ISetpointRepository { private readonly DbContext db; public SetpointRepository(DbContext db) { this.db = db; } protected virtual IQueryable GetQueryReadOnly() => db.Set(); public async Task> GetCurrent( IEnumerable setpointKeys, CancellationToken token) { var query = GetQueryReadOnly(); var entities = await query .Where(e => setpointKeys.Contains(e.Key)) .GroupBy(e => e.Key) .Select(g => g.OrderByDescending(x => x.Timestamp).FirstOrDefault()) .ToArrayAsync(token); var dtos = entities.Select(e => e.Adapt()); return dtos; } public async Task> GetCurrentDictionary(IEnumerable setpointKeys, CancellationToken token) { var query = GetQueryReadOnly(); var entities = await query .Where(e => setpointKeys.Contains(e.Key)) .GroupBy(e => e.Key) .Select(g => g.OrderByDescending(x => x.Timestamp).FirstOrDefault()) .ToDictionaryAsync(x=> x.Key, x => (object)x.Value, token); return entities; } public async Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token) { var query = GetQueryReadOnly(); var entities = await query .Where(e => setpointKeys.Contains(e.Key)) .ToArrayAsync(token); var filteredEntities = entities .GroupBy(e => e.Key) .Select(e => e.OrderBy(o => o.Timestamp)) .Select(e => e.Where(e => e.Timestamp <= historyMoment).Last()); var dtos = filteredEntities .Select(e => e.Adapt()); return dtos; } public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) { var query = GetQueryReadOnly(); var entities = await query .Where(e => e.Timestamp >= dateBegin) .Take(take) .ToArrayAsync(token); var dtos = entities .Select(e => e.Adapt()); return dtos; } public async Task GetDatesRangeAsync(CancellationToken token) { var query = GetQueryReadOnly() .GroupBy(e => 1) .Select(group => new { Min = group.Min(e => e.Timestamp), Max = group.Max(e => e.Timestamp), }); var values = await query.FirstOrDefaultAsync(token); var result = new DatesRangeDto() { From = values?.Min ?? DateTimeOffset.MinValue, To = values?.Max ?? DateTimeOffset.MaxValue }; return result; } public async Task>> GetLog(IEnumerable setpointKeys, CancellationToken token) { var query = GetQueryReadOnly(); var entities = await query .Where(e => setpointKeys.Contains(e.Key)) .ToArrayAsync(token); var dtos = entities .GroupBy(e => e.Key) .ToDictionary(e => e.Key, v => v.Select(z => z.Adapt())); return dtos; } public async Task Add(Guid setpointKey, JsonElement newValue, Guid idUser, CancellationToken token) { var entity = new Setpoint() { Key = setpointKey, Value = newValue, IdUser = idUser, Timestamp = DateTimeOffset.UtcNow.ToUniversalTime() }; await db.Set().AddAsync(entity, token); await db.SaveChangesAsync(token); } } }