commit ba41c9635b64598fbaa66f6e2f8881dfa5c878a0
Author: hlavja <hlavjah@gmail.com>
Date:   Thu May 6 15:34:41 2021 +0200

    Re #8851 - Unit page - implementace
    
    + adding observations support
    + get for every selected sensor instead of get all
    + use stored data if date is not changed

diff --git a/src/app/unit/components/unit.component.ts b/src/app/unit/components/unit.component.ts
index d21157b..3944de3 100644
--- a/src/app/unit/components/unit.component.ts
+++ b/src/app/unit/components/unit.component.ts
@@ -1,7 +1,7 @@
 import {Component, OnInit} from '@angular/core';
 import {ActivatedRoute} from '@angular/router';
 import {AnalyticsService} from '../../shared/api/endpoints/services/analytics.service';
-import {map} from 'rxjs/operators';
+import {map, tap} from 'rxjs/operators';
 import {AggregationModel} from '../../shared/models/aggregationModel';
 import * as moment from 'moment-timezone';
 import {GraphLoader} from '../../shared/graph-loading/graphloader';
@@ -9,6 +9,7 @@ import {SensorsService} from '../../shared/api/endpoints/services/sensors.servic
 import {HttpResponse} from '@angular/common/http';
 import {ToastService} from '../../shared/services/toast.service';
 import {Sensor} from '../../shared/api/endpoints/models/sensor';
+import {ObservationService} from '../../shared/api/endpoints/services/observation.service';
 
 
 @Component({
@@ -29,17 +30,19 @@ export class UnitComponent implements OnInit {
   analyticsData: any[] = [];
   observationsData: any[] = [];
   sensorGroups = [];
-  selectedSensors: any[] = [];
+  selectedSensors: number[] = [];
   sensors: Sensor[];
   showAggregation = false;
   aggregationFunction: AggregationModel[];
-  selectedAggregationFunction = 'HOUR';
+  selectedAggregationFunction = 'DAY';
+  useAnalyticsData = false;
 
   constructor(
     private activatedRoute: ActivatedRoute,
     private analyticsService: AnalyticsService,
     private sensorService: SensorsService,
-    private toastService: ToastService
+    private toastService: ToastService,
+    private observationService: ObservationService
   ) {
     this.unitId = parseInt(this.activatedRoute.snapshot.paramMap.get('unitId'), 10);
     this.aggregationFunction = [
@@ -49,35 +52,35 @@ export class UnitComponent implements OnInit {
       {name: 'Year', code: 'YEAR'}
     ];
     this.today = moment().toDate();
-    this.sensorService.getUnitSensors({unit_id: this.unitId}).subscribe(
-      sensors => {
-        this.sensors = sensors;
-        if (sensors) {
-          sensors.forEach(sensor => {
+    this.sensorService.getUnitSensors({unit_id: this.unitId}).pipe(
+      tap(sens => {
+        this.sensors = sens;
+      }),
+      tap(() => {
+        if (this.sensors && this.sensors.length > 0) {
+          this.sensors.forEach(sensor => {
             const sensorType = sensor.sensorId.toString().slice(0, 5);
             if (!this.sensorGroups.some(group => group === sensorType)) {
               this.sensorGroups.push(sensorType);
               setTimeout(() => {
-                  GraphLoader.getGraph(null, null, null, '#vega_container_' + sensor.sensorId.toString().slice(0, 5));
+                GraphLoader.getGraph(null, null, null, '#vega_container_' + sensor.sensorId.toString().slice(0, 5));
               }, 0);
             }
             if (!this.selectedSensors.some(sens => sens.toString().slice(0, 5) === sensorType)) {
               this.selectedSensors.push(sensor.sensorId);
             }
           })
+          this.showGraph();
         }
-      }
-    );
+      })
+    ).toPromise().then();
   }
 
   ngOnInit(): void {
-    setTimeout(() => {
-      this.showGraph();
-    }, 0);
   }
 
-  showGraph() {
-    const range: Date[] = [moment().subtract(6, 'months').toDate(), moment().toDate()];
+  showGraph(changedDate: boolean = true, changedSensor: number = null) {
+    const range: Date[] = [moment().subtract(7, 'months').toDate(), moment().toDate()];
 
     if (this.from && !this.to || !this.from && this.to) {
       return;
@@ -89,53 +92,162 @@ export class UnitComponent implements OnInit {
     }
 
     if (moment(range[1]).diff(moment(range[0]), 'days') > 7) {
+      this.useAnalyticsData = true;
       this.showAggregation = true;
-      this.getAnalytics(range);
+      this.getAnalytics(range, changedDate, changedSensor);
     } else {
+      this.useAnalyticsData = false;
       this.showAggregation = false;
-      // this.getObservations(range);
+      this.getObservations(range, changedDate, changedSensor);
     }
   }
 
-  getAnalytics(range: Date[]) {
-    this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: null,
-      from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
-      to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
-      map((response: HttpResponse<any>) => {
-        if (response.status === 200) {
-          return response.body;
-        } else if (response.status === 204) {
-          this.toastService.showWarningNoData();
-          return response.body;
-        } else {
-          return false;
-        }
-      })
-    ).subscribe(data => {
-      if (data) {
-        this.analyticsData = data;
-        const objectKeys = Object.keys(data);
+  getAnalytics(range: Date[], changedDate: boolean, changedSensor: number) {
+    if (changedDate) {
+      this.selectedSensors.forEach(selectSens => {
+        this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: selectSens,
+          from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
+          to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
+          map((response: HttpResponse<any>) => {
+            if (response.status === 200) {
+              return response.body;
+            } else if (response.status === 204) {
+              this.toastService.showWarningNoData();
+              return response.body;
+            } else {
+              return false;
+            }
+          })
+        ).subscribe(data => {
+          if (data) {
+            this.analyticsData.push({sensorId: selectSens, data: data[selectSens].data});
+            const objectKeys = Object.keys(data);
+            for(const key of objectKeys ) {
+              if (data[key].data) {
+                const view = '#vega_container_' + key.slice(0, 5);
+                if (this.selectedSensors.some(sens => sens.toString() === key)) {
+                  GraphLoader.getGraph(key, data[key].data, data[key].interval, view);
+                } else {
+                  GraphLoader.getGraph(null, null, null, view);
+                }
+              }
+            }
+          }
+        }, err => this.toastService.showError(err.error.message));
+      });
+    } else  {
+      this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: changedSensor,
+        from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
+        to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
+        map((response: HttpResponse<any>) => {
+          if (response.status === 200) {
+            return response.body;
+          } else if (response.status === 204) {
+            this.toastService.showWarningNoData();
+            return response.body;
+          } else {
+            return false;
+          }
+        })
+      ).subscribe(data => {
+        if (data) {
+          this.analyticsData.push({sensorId: changedSensor, data: data[changedSensor].data, interval: data[changedSensor].interval});
+          const objectKeys = Object.keys(data);
           for(const key of objectKeys ) {
             if (data[key].data) {
               const view = '#vega_container_' + key.slice(0, 5);
               if (this.selectedSensors.some(sens => sens.toString() === key)) {
                 GraphLoader.getGraph(key, data[key].data, data[key].interval, view);
+              } else {
+                GraphLoader.getGraph(null, null, null, view);
               }
             }
           }
         }
       }, err => this.toastService.showError(err.error.message));
+    }
   }
 
   addSensorToGraph(sensorId: number) {
-    const objectKeys = Object.keys(this.analyticsData);
-    for(const key of objectKeys ) {
-      if (this.analyticsData[key].data) {
-        const view = '#vega_container_' + key.slice(0, 5);
-        if (sensorId.toString() === key) {
-          GraphLoader.getGraph(key, this.analyticsData[key].data, this.analyticsData[key].interval, view);
+    if (!this.selectedSensors.some(sensId => sensId.toString().slice(0, 5) === sensorId.toString().slice(0, 5))) {
+      GraphLoader.getGraph(null, null, null, '#vega_container_' + sensorId.toString().slice(0, 5));
+    } else {
+      if (this.useAnalyticsData) {
+        if (this.analyticsData.some(sens => sens.sensorId === sensorId)) {
+          console.log(this.analyticsData.find(sens => sens.sensorId === sensorId).data);
+          GraphLoader.getGraph(sensorId, this.analyticsData.find(sens => sens.sensorId === sensorId).data,
+            this.analyticsData.find(sens => sens.sensorId === sensorId).interval, '#vega_container_' + sensorId.toString().slice(0, 5));
+        } else {
+          this.showGraph(false, sensorId);
+        }
+      } else {
+        if (this.observationsData.some(sens => sens.sensorId === sensorId)) {
+          GraphLoader.getObservationGraph(sensorId,
+            this.observationsData.find(sens => sens.sensorId === sensorId).data, '#vega_container_' + sensorId.toString().slice(0, 5));
+        } else {
+          this.showGraph(false, sensorId);
         }
       }
     }
   }
+
+  private getObservations(range: Date[], changedDate: boolean, changedSensor: number) {
+    if (changedDate) {
+      this.selectedSensors.forEach(selectSens => {
+        this.observationService.getObservation$Response({
+          unit_id: this.unitId,
+          sensor_id: selectSens,
+          from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
+          to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3)
+        }).pipe(
+          map((response: HttpResponse<any>) => {
+            if (response.status === 200) {
+              return response.body;
+            } else if (response.status === 204) {
+              this.toastService.showWarningNoData();
+              return response.body;
+            } else {
+              return false;
+            }
+          })
+        ).subscribe(
+          observations => {
+            this.observationsData.push({sensorId: selectSens, data: observations});
+            const view = '#vega_container_' + selectSens.toString().slice(0, 5);
+            if (observations) {
+              GraphLoader.getObservationGraph(selectSens, observations, view);
+            } else {
+              GraphLoader.getObservationGraph(null, null, null);
+            }
+          }, err => this.toastService.showError(err.error.message));
+      });
+    } else {
+      this.observationService.getObservation$Response({
+        unit_id: this.unitId,
+        sensor_id: changedSensor,
+        from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
+        to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3)
+      }).pipe(
+        map((response: HttpResponse<any>) => {
+          if (response.status === 200) {
+            return response.body;
+          } else if (response.status === 204) {
+            this.toastService.showWarningNoData();
+            return response.body;
+          } else {
+            return false;
+          }
+        })
+      ).subscribe(
+        observations => {
+          this.observationsData.push({sensorId: this.selectedSensors[0], data: observations});
+          const view = '#vega_container_' + changedSensor.toString().slice(0, 5);
+          if (observations) {
+            GraphLoader.getObservationGraph(changedSensor, observations, view);
+          } else {
+            GraphLoader.getObservationGraph(null, null, null);
+          }
+        }, err => this.toastService.showError(err.error.message));
+    }
+  }
 }
