using Mapster; using Microsoft.EntityFrameworkCore; using Persistence.Database.Model; using Persistence.Models; using Persistence.Repositories; namespace Persistence.Repository.Repositories { public class SetpointRepository : ISetpointRepository { private 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)) .ToArrayAsync(token); var dtos = entities.Select(e => e.Adapt()); return dtos; } 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.Where(e => e.Created <= historyMoment).Last()); var dtos = filteredEntities .Select(e => e.Adapt()); return dtos; } 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 Save(Guid setpointKey, object newValue, int idUser, CancellationToken token) { var entity = new Setpoint() { Key = setpointKey, Value = newValue, IdUser = idUser, Created = DateTimeOffset.UtcNow }; await db.Set().AddAsync(entity, token); await db.SaveChangesAsync(token); } } }