DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/TelemetryService.cs

79 lines
2.8 KiB
C#

using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Mapster;
using System.Linq;
namespace AsbCloudInfrastructure.Services
{
public class TelemetryService : ITelemetryService
{
private readonly CacheTable<Telemetry> cacheTelemetry;
private readonly CacheTable<Well> cacheWells;
private readonly IAsbCloudDbContext db;
public TelemetryService(IAsbCloudDbContext db, CacheDb cacheDb)
{
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
this.db = db;
}
public int GetOrCreateTemetryIdByUid(string uid)
=> GetOrCreateTelemetryByUid(uid).Id;
public int? GetidWellByTelemetryUid(string uid)
=> GetWellByTelemetryUid(uid)?.Id;
public double GetTimezoneOffsetByTelemetryId(int idTelemetry) =>
cacheTelemetry.FirstOrDefault(t => t.Id == idTelemetry).Info?.TimeZoneOffsetTotalHours??0d;
public void UpdateInfo(string uid, TelemetryInfoDto info)
{
var telemetry = GetOrCreateTelemetryByUid(uid);
telemetry.Info = info.Adapt<TelemetryInfo>();
cacheTelemetry.Upsert(telemetry);
}
public int? GetIdTelemetryByIdWell(int idWell)
{
var well = cacheWells.FirstOrDefault(w => w.Id == idWell);
if (well is null)
return null;
return well.IdTelemetry;
}
private Well GetWellByTelemetryUid(string uid)
{
var tele = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid, RefreshMode.IfResultEmpty);
if (tele is null)
return null;
return cacheWells.FirstOrDefault(w => w?.IdTelemetry == tele.Id);
}
// TODO: fix cacheTable before uncomment next
//private Telemetry GetOrCreateTelemetryByUid(string uid)
// => cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid)
// ?? cacheTelemetry.Insert(new Telemetry { RemoteUid = uid, });
private Telemetry GetOrCreateTelemetryByUid(string uid)
{
var telemetry = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid);
if (telemetry is not null)
return telemetry;
telemetry = db.Telemetries.OrderBy(t=>t.Info).FirstOrDefault(t => t.RemoteUid == uid);
if (telemetry is not null)
return telemetry;
var newTelemetryEntry = db.Telemetries.Add(new Telemetry { RemoteUid = uid });
db.SaveChanges();
cacheTelemetry.Refresh();
return newTelemetryEntry.Entity;
}
}
}