From 4a91a29f0743ddd2434dde134a467418d04199fd Mon Sep 17 00:00:00 2001
From: ngfrolov <ng.frolov@autodrilling.ru>
Date: Mon, 25 Apr 2022 12:17:14 +0500
Subject: [PATCH] Rename DetectedOperation props simmmilar to WellOperation

---
 .../DetectOperations/DetectedOperation.cs     | 14 ++--
 .../DetectOperations/DetectorAbstract.cs      | 10 +--
 .../DetectOperations/DetectorService.cs       | 70 +++++++++++++++++--
 3 files changed, 77 insertions(+), 17 deletions(-)

diff --git a/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperation.cs b/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperation.cs
index 9eb6aaae..8aa3417f 100644
--- a/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperation.cs
+++ b/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperation.cs
@@ -4,16 +4,16 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
 {
     public class DetectedOperation
     {
-        public int IdType { get; set; }
+        public int IdCategory { get; set; }
         public int IdUsersAtStart { get; set; }
-        public DateTimeOffset Begin { get; set; }
-        public DateTimeOffset End { get; set; }
-        public double DurationMinutes => (End - Begin).TotalMinutes;
-        public double BeginWellDepth { get; set; }
-        public double EndWellDepth { get; set; }
+        public DateTimeOffset DateStart { get; set; }
+        public DateTimeOffset DateEnd { get; set; }
+        public double DurationMinutes => (DateEnd - DateStart).TotalMinutes;
+        public double DepthStart { get; set; }
+        public double DepthEnd { get; set; }
 
         public override string ToString()
-            => $"{IdType}\t{Begin:G}\t{End:G}\t{DurationMinutes:#0.#}\t{BeginWellDepth:#0.#}\t{EndWellDepth:#0.#}";
+            => $"{IdCategory}\t{DateStart:G}\t{DateEnd:G}\t{DurationMinutes:#0.#}\t{DepthStart:#0.#}\t{DepthEnd:#0.#}";
             //=> $"{{\"type\": {IdType},\t\"begin\":\"{Begin:G}\",\t\"end\":\"{End:G}\",\t\"depthBegin\":\"{BeginWellDepth:#0.#}\",\t\"depthEnd\":\"{EndWellDepth:#0.#}\"}}";
     }
 }
\ No newline at end of file
diff --git a/AsbCloudInfrastructure/Services/DetectOperations/DetectorAbstract.cs b/AsbCloudInfrastructure/Services/DetectOperations/DetectorAbstract.cs
index dfb434d3..24911a25 100644
--- a/AsbCloudInfrastructure/Services/DetectOperations/DetectorAbstract.cs
+++ b/AsbCloudInfrastructure/Services/DetectOperations/DetectorAbstract.cs
@@ -44,12 +44,12 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
                     {
                         var result = new DetectedOperation
                         {
-                            IdType = IdOperationType,
+                            IdCategory = IdOperationType,
                             IdUsersAtStart = telemetry[position].IdUser ?? -1,
-                            Begin = telemetry[position].DateTime,
-                            End = telemetry[skip].DateTime,
-                            BeginWellDepth = telemetry[position].WellDepth ?? -1d,
-                            EndWellDepth = telemetry[skip].WellDepth ?? -1d,
+                            DateStart = telemetry[position].DateTime,
+                            DateEnd = telemetry[skip].DateTime,
+                            DepthStart = telemetry[position].WellDepth ?? -1d,
+                            DepthEnd = telemetry[skip].WellDepth ?? -1d,
                         };
                         position = skip + FragmentLength;
                         return result;
diff --git a/AsbCloudInfrastructure/Services/DetectOperations/DetectorService.cs b/AsbCloudInfrastructure/Services/DetectOperations/DetectorService.cs
index 0e8fe1d3..0980a039 100644
--- a/AsbCloudInfrastructure/Services/DetectOperations/DetectorService.cs
+++ b/AsbCloudInfrastructure/Services/DetectOperations/DetectorService.cs
@@ -1,16 +1,19 @@
 using AsbCloudDb.Model;
 using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Hosting;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading;
 using System.Threading.Tasks;
+using System.Diagnostics;
 
 namespace AsbCloudInfrastructure.Services.DetectOperations
 {
-    public class DetectorService
+    public class OperationDetectorBackgroundService : BackgroundService
     {
-        readonly IEnumerable<DetectorAbstract> detectors = new List<DetectorAbstract>
+        private readonly IEnumerable<DetectorAbstract> detectors = new List<DetectorAbstract>
         {
             new Detectors.DetectorSlipsTime(),
             // new Detectors.DetectorDrillingRotor(),
@@ -19,17 +22,74 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
 
         private readonly int minStepLength;
         private readonly int minFragmentLength;
+        private readonly string connectionString;
+        private readonly TimeSpan period = TimeSpan.FromHours(1);
 
-        public DetectorService()
+        public OperationDetectorBackgroundService(IConfiguration configuration)
         {
             minStepLength = detectors.Min(d => d.StepLength);
             minStepLength = minStepLength > 0 ? minStepLength : 3;
 
             minFragmentLength = detectors.Min(d => d.FragmentLength);
             minFragmentLength = minFragmentLength > 0 ? minFragmentLength : 6;
+
+            connectionString = configuration.GetConnectionString("DefaultConnection");
         }
 
-        public async Task<IEnumerable<DetectedOperation>> DetectOperationsAsync(int idTelemetry, DateTimeOffset begin, IAsbCloudDbContext db, CancellationToken token)
+        protected override async Task ExecuteAsync(CancellationToken token = default)
+        {
+            var timeToStartAnalysis = DateTime.Now;
+            var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
+                .UseNpgsql(connectionString)
+                .Options;
+
+            while (!token.IsCancellationRequested)
+            {
+                if (DateTime.Now > timeToStartAnalysis)
+                {
+                    timeToStartAnalysis = DateTime.Now + period;
+                    try
+                    {
+                        using var context = new AsbCloudDbContext(options);
+                        
+                    }
+                    catch (Exception ex)
+                    {
+                        Trace.TraceError(ex.Message);
+                        Console.WriteLine(ex.Message);
+                    }
+                    GC.Collect();
+                }
+
+                var ms = (int)(timeToStartAnalysis - DateTime.Now).TotalMilliseconds;
+                ms = ms > 100 ? ms : 100;
+                await Task.Delay(ms, token).ConfigureAwait(false);
+            }
+        }
+
+        public override async Task StopAsync(CancellationToken token)
+        {
+            await base.StopAsync(token).ConfigureAwait(false);
+        }
+
+        private async Task<DateTime> GetLastAnalysisDateAsync(int idTelemetry, IAsbCloudDbContext db, CancellationToken token)
+        {
+            var lastAnalysisInDb = await (from analysis in db.TelemetryAnalysis
+                                          where analysis.IdTelemetry == idTelemetry
+                                          orderby analysis.UnixDate
+                                          select analysis)
+                                    .LastOrDefaultAsync(token)
+                                    .ConfigureAwait(false);
+
+            DateTime lastAnalysisDate = new DateTime(0, DateTimeKind.Utc);
+
+            if (lastAnalysisInDb is not null)
+                lastAnalysisDate = DateTime.UnixEpoch.AddSeconds(lastAnalysisInDb.DurationSec + lastAnalysisInDb.UnixDate);
+
+            return lastAnalysisDate;
+        }
+
+        private async Task<IEnumerable<DetectedOperation>> DetectOperationsAsync(int idTelemetry, DateTimeOffset begin, IAsbCloudDbContext db, CancellationToken token)
         {
             var query = db.TelemetryDataSaub
                 .AsNoTracking()
@@ -90,7 +150,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
                             isDetected1 = true;
                             isDetected = true;
                             detectedOperations.Add(detectedOperation);
-                            startDate = detectedOperation.End;
+                            startDate = detectedOperation.DateEnd;
                             break;
                         }
                     }