using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; using AsbCloudApp.Services; using AsbCloudDb.Model; using Microsoft.EntityFrameworkCore; namespace AsbCloudInfrastructure.Services { public class DrillParamsService : CrudServiceBase, IDrillParamsService { private readonly IAsbCloudDbContext db; private readonly ITelemetryService telemetryService; public DrillParamsService(IAsbCloudDbContext context, ITelemetryService telemetryService) : base(context) { this.telemetryService = telemetryService; } public async Task GetDefaultDrillParamsAsync(int idWell, double startDepth, double endDepth, CancellationToken token = default) { var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell); if (idTelemetry is null) return null; var axialLoads = await GetDrillParams(idWell, startDepth, endDepth, (telemetry) => telemetry.AxialLoad, token); var pressures = await GetDrillParams(idWell, startDepth, endDepth, (telemetry) => telemetry.Pressure, token); var drillParamsDto = new DrillParamsDto() { IdWell = idWell, DepthStart = startDepth, DepthEnd = endDepth, AxialLoadMin = axialLoads.Min, AxialLoadAvg = axialLoads.Avg, AxialLoadMax = axialLoads.Max, PressureMin = pressures.Min, PressureAvg = pressures.Avg, PressureMax = pressures.Max, // TopDriveTorqueMin = topDriveTorques.Min ?? 0, // TopDriveTorqueAvg = topDriveTorques.Avg ?? 0, // TopDriveTorqueMax = topDriveTorques.Max ?? 0, // TopDriveSpeedMin = topDriveSpeeds.Min ?? 0, // TopDriveSpeedAvg = topDriveSpeeds.Avg ?? 0, // TopDriveSpeedMax = topDriveSpeeds.Max ?? 0, // ConsumptionMin = consumptions.Min ?? 0, // ConsumptionAvg = consumptions.Avg ?? 0, // ConsumptionMax = consumptions.Max ?? 0, }; return drillParamsDto; } private async Task<(double Min, double Avg, double Max)> GetDrillParams(int idTelemetry, double startDepth, double endDepth, Func func, CancellationToken token = default) { var res = await (from telemetry in db.TelemetryDataSaub where telemetry.IdTelemetry == idTelemetry && telemetry.WellDepth >= startDepth && telemetry.WellDepth <= endDepth group telemetry by telemetry.IdTelemetry into g select new { Min = g.Min(func), Avg = g.Average(func), Max = g.Max(func) }) .DefaultIfEmpty() .AsNoTracking() .FirstOrDefaultAsync(token) .ConfigureAwait(false); return (res.Min ?? 0, res.Avg ?? 0, res.Max ?? 0); } } }