From e96c48c723afc7a7171f92e349d395a6a80f47d4 Mon Sep 17 00:00:00 2001
From: csba1652 <Bilal.Hassan@student.uibk.ac.at>
Date: Sun, 19 Feb 2023 19:30:11 +0100
Subject: [PATCH] working on expert view adding dowload functionality

---
 src/app/app.module.ts                         | 36 +++++++------
 .../light-chart.component.ts                  | 53 +++++++++++++++---
 .../pro-view/pro-view.component.html          | 23 +++-----
 .../components/pro-view/pro-view.component.ts | 54 ++++++++++++++++++-
 4 files changed, 123 insertions(+), 43 deletions(-)

diff --git a/src/app/app.module.ts b/src/app/app.module.ts
index 99ecdaf..9c83d10 100644
--- a/src/app/app.module.ts
+++ b/src/app/app.module.ts
@@ -39,6 +39,7 @@ import {MatCheckboxModule} from "@angular/material/checkbox";
 import {ApiModule} from "../../projects/swagger-client/src";
 import { InterceptorService } from './shared/auth/interceptor.service';
 import {CjsTimelineMultiple} from "./module/components/charts/Cjs-timeline-multiple/light-chart.component";
+import {MatButtonModule} from "@angular/material/button";
 
 @NgModule({
   declarations: [
@@ -67,23 +68,24 @@ import {CjsTimelineMultiple} from "./module/components/charts/Cjs-timeline-multi
     CjsTimelineMultiple
 
   ],
-    imports: [
-        BrowserModule,
-        AppRoutingModule,
-        ReactiveFormsModule,
-        HttpClientModule,
-        FormsModule,
-        BrowserAnimationsModule,
-        MatIconModule,
-        MatFormFieldModule,
-        MatSelectModule,
-        MatDatepickerModule,
-        MatInputModule,
-        MatNativeDateModule,
-        MatAutocompleteModule,
-        MatCheckboxModule,
-      ApiModule,
-    ],
+  imports: [
+    BrowserModule,
+    AppRoutingModule,
+    ReactiveFormsModule,
+    HttpClientModule,
+    FormsModule,
+    BrowserAnimationsModule,
+    MatIconModule,
+    MatFormFieldModule,
+    MatSelectModule,
+    MatDatepickerModule,
+    MatInputModule,
+    MatNativeDateModule,
+    MatAutocompleteModule,
+    MatCheckboxModule,
+    ApiModule,
+    MatButtonModule,
+  ],
   providers: [EventEmitterService,{provide:HTTP_INTERCEPTORS,useClass:InterceptorService,multi:true}],
   bootstrap: [AppComponent],
 })
diff --git a/src/app/module/components/charts/Cjs-timeline-multiple/light-chart.component.ts b/src/app/module/components/charts/Cjs-timeline-multiple/light-chart.component.ts
index e42dad6..6349495 100644
--- a/src/app/module/components/charts/Cjs-timeline-multiple/light-chart.component.ts
+++ b/src/app/module/components/charts/Cjs-timeline-multiple/light-chart.component.ts
@@ -26,7 +26,10 @@ export class CjsTimelineMultiple implements OnInit,OnChanges{
 
   @Input() chartId:String="test"
   @Input() sensorData!:SensorData[]
+  @Input() sensorDataArray!:[SensorData[]]
   dataParent:Number[]=[]
+  dataParentArray:[Number[]]=[[]]
+
   timeStampsAsHour:any
   coloredData:any
   colorMapper = new Map<String, String>([
@@ -82,11 +85,17 @@ export class CjsTimelineMultiple implements OnInit,OnChanges{
     let datePipe = new DatePipe('en-US');
     this.timeStampsAsHour=timeStamp.map(x=>datePipe.transform(x,'HH:mm'))
     this.logger.info("Timeline got from Server #gS",this.timeStampsAsHour)
-    // @ts-ignore
-    this.coloredData=this.sensorData[0].readings.map(y=>this.colorMapper.get(y.fluctuationType))
-    // @ts-ignore
-    this.logger.info("Data Code #gS",this.coloredData);
     this.logger.info("Finished Mapping data")
+
+    console.log("from childArray",this.sensorDataArray)
+    // this.dataParentArray=this.sensorDataArray.map(x=>x.map(y=>y.readings.map(z=>z.value).flat()))
+    this.dataParentArray=[[]]
+    this.sensorDataArray.forEach(
+      sensDat=>{
+        this.dataParentArray.push(sensDat.map(x=>x.readings.map(y=>y.value)).flat())
+      }
+    )
+    console.log("filterd array child",this.dataParentArray)
   }
 
    ngAfterViewInit() {
@@ -101,13 +110,43 @@ export class CjsTimelineMultiple implements OnInit,OnChanges{
     /**********THIS FUNCTION WILL TRIGGER WHEN PARENT COMPONENT UPDATES 'someInput'**************/
     //Write your code here
     this.mapData()
-    this.linConfig.data.labels=this.timeStampsAsHour
-    this.linConfig.data.datasets[0].data=this.dataParent
+   this.linConfig.data.labels=this.timeStampsAsHour
+  //  this.linConfig.data.labels= Array(47).fill(0).map((_, i) => i);
+  //  for (let i = 0; i < 3; i++) {
+     // if(i>1)
+     //   this.linConfig.data.datasets[i-2].data=this.dataParentArray[i]
+    let names: string[] = [];
+    this.sensorDataArray.forEach(dat => {
+      if (dat && dat[0] && dat[0].sensorName) {
+        names.push(dat[0].sensorName);
+      }})
+  console.log("sensorname",names)
+    const data = Array.from({ length: this.sensorDataArray.length }, (_, i) => (
+      {
+      label:`Dataset ${i+1}`+names.at(i),
+      backgroundColor:( getRandomColor()+'0.1)'),
+      fill:true,
+      borderColor:(getRandomColor()+'0.8)'),
+      tension:0.2,
+      data:this.dataParentArray.at(i+2),
+    }));
+
+    function getRandomColor(): string {
+      const r = Math.floor(Math.random() * 256);
+      const g = Math.floor(Math.random() * 256);
+      const b = Math.floor(Math.random() * 256);
+      return `rgba(${r}, ${g}, ${b}, `;
+    }
+    this.linConfig.data.datasets=data
+    // }
+   // if(this.dataParentArray.length<3)
+   //   this.linConfig.data.datasets[0].data=this.dataParent
 //    this.linConfig.data.datasets[0].pointBorderColor=this.coloredData
 //    this.linConfig.data.datasets[0].pointBackgroundColor=this.coloredData
  //   this.linechart.data = this.linConfig.data;
     console.log("channnged")
-    this.linechart.update();
+    if(this.linechart !== undefined)
+      this.linechart.update();
   }
 
 }
diff --git a/src/app/module/components/pro-view/pro-view.component.html b/src/app/module/components/pro-view/pro-view.component.html
index db2273d..95fda6c 100644
--- a/src/app/module/components/pro-view/pro-view.component.html
+++ b/src/app/module/components/pro-view/pro-view.component.html
@@ -81,37 +81,26 @@
   </mat-form-field>
 </form>
 
-<div class="flex flex-wrap w-full justify-center sm:justify-between
+<div class="flex flex-wrap w-full justify-center sm:justify-end
              [&>*]:w-full [&>*]:sm:w-1/4  [&>*]:h-16  [&>*]:p-2 ">
-
+<!--
   <div class="">
     <section class="bg-slate-100 h-full w-full flex items-center rounded-2xl">
       <mat-checkbox [(ngModel)]="isChecked" class="m-2">Select Me</mat-checkbox>
     </section>
   </div>
+-->
 
   <div class="">
-    <section class="bg-slate-100 h-full w-full flex items-center rounded-2xl">
-      <mat-checkbox class="m-2">Select Me</mat-checkbox>
-    </section>
-  </div>
-
-  <div class="">
-    <section class="bg-slate-100 h-full w-full flex items-center rounded-2xl">
-      <mat-checkbox class="m-2">Select Me</mat-checkbox>
-    </section>
-  </div>
-
-  <div class="">
-    <section class="bg-slate-100 h-full w-full flex items-center rounded-2xl">
-      <mat-checkbox class="m-2">Select Me</mat-checkbox>
+    <section class=" h-full w-full flex items-center rounded-2xl">
+      <button class="w-full h-full" mat-raised-button color="primary" (click)="downloadCSV4()">Download Data <mat-icon>download</mat-icon></button>
     </section>
   </div>
 
 </div>
 <button (click)="downloadCSV()">Download</button>
 
-<app-Cjs-timeline-multiple [sensorData]="this.sensorData" ></app-Cjs-timeline-multiple>
+<app-Cjs-timeline-multiple [sensorData]="this.sensorData" [sensorDataArray]="this.sensorDataArray" ></app-Cjs-timeline-multiple>
 {{isChecked}}
 {{this.selectedHostClient}}
 
diff --git a/src/app/module/components/pro-view/pro-view.component.ts b/src/app/module/components/pro-view/pro-view.component.ts
index 5feafa2..636d198 100644
--- a/src/app/module/components/pro-view/pro-view.component.ts
+++ b/src/app/module/components/pro-view/pro-view.component.ts
@@ -10,6 +10,7 @@ import {
 } from "../../../../../projects/swagger-client/src";
 
 import {DatePipe} from "@angular/common";
+import {List} from "postcss/lib/list";
 
 
 @Component({
@@ -49,6 +50,7 @@ export class ProViewComponent {
   })
 
   sensorData:SensorData[]=[]
+  sensorDataArray:[SensorData[]]=[[]]
 
   data: any[] = [
     { name: 'John', age: 28, city: 'New York' },
@@ -194,7 +196,13 @@ export class ProViewComponent {
   }
 
   downloadCSV() {
-    const csv = this.convertToCSV(this.data);
+    const transformedData = this.sensorData.map(data => ({
+      timestamp: data.timestamp,
+      Sensor_name:data.sensorName,
+      Sensor_id: data._id,
+      values: data.readings.map(reading => reading.value),
+    }));
+    const csv = this.convertToCSV(transformedData);
     const blob = new Blob([csv], { type: 'text/csv' });
     const url = window.URL.createObjectURL(blob);
 
@@ -202,11 +210,49 @@ export class ProViewComponent {
     const a = document.createElement('a');
     a.style.display = 'none';
     a.href = url;
-    a.download = 'data.csv';
+    a.download = 'forte-sensor-data.csv';
     document.body.appendChild(a);
     a.click();
   }
 
+  downloadCSV4() {
+    // Use the first timestamp in each array of sensorDataArray as the timestamp for each row
+    let csvData:any[]=[[]]
+    csvData.push()
+    const timestamps = this.sensorDataArray.at(1)?.map(data => data.timestamp?? '')??[];
+    console.log("timestamo vsc4",timestamps)
+   const sensorData: any[] = [];
+   this.sensorDataArray.forEach((sD,i)=>{
+     sensorData.push(   sD.map(data => ({
+        timestamp: data.timestamp,
+       [data.sensorName]: data.readings.map(reading => reading.value),
+      })) );
+    })
+    console.log("sensodata csv",sensorData)
+    let transformedData = timestamps.map((timestamp, i) => ({
+      timestamp: timestamp
+    }));
+    for (let i = 1; i < sensorData.length; i++) {
+      transformedData= transformedData.map((obj, ii) => {
+        return { ...obj, ...sensorData[i][ii] };
+      });
+    }
+
+  console.log("merged",transformedData)
+    const csv = this.convertToCSV(transformedData);
+    const blob = new Blob([csv], { type: 'text/csv' });
+    const url = window.URL.createObjectURL(blob);
+    // Create a link element and click it to trigger the download
+    const a = document.createElement('a');
+    a.style.display = 'none';
+    a.href = url;
+    a.download = 'forte-sensor-data.csv';
+    document.body.appendChild(a);
+    a.click();
+    document.body.removeChild(a);
+  }
+
+
   onSelectionChange(event: checkHostsStation[]) {
     console.log(this.selectedHostClient,"selected host clients")
     this.availableSensors=[]
@@ -229,6 +275,7 @@ export class ProViewComponent {
 
   onSelectionChange2(event: string[]) {
     this.sensorData=[]
+    this.sensorDataArray=[[]]
       console.log("final sensor",event)
     console.log(this.range.value)
     console.log("tooooooping",this.toppings.value)
@@ -249,11 +296,14 @@ export class ProViewComponent {
               console.log(s)
               // @ts-ignore
               this.sensorData=s
+              this.sensorDataArray.push(this.sensorData)
               console.log("sensor data",this.sensorData)
+              console.log("array sensor Data",this.sensorDataArray)
             },
             error => console.error("error")
           )
         )
+
       }
   }
 
-- 
GitLab