import { AfterViewInit, Component, OnInit } from '@angular/core'; import { ChartDataSets, ChartOptions } from 'chart.js'; import { Label } from 'ng2-charts'; import * as moment from 'moment'; import { APIService, IBeat } from '../api.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'] }) export class DashboardComponent implements AfterViewInit { totalDistance = '0'; devices = 0; // Array of different segments in chart lineChartData: ChartDataSets[] = [ { data: [], label: 'Battery' } ]; // Labels shown on the x-axis lineChartLabels: Label[] = []; // Define chart options lineChartOptions: ChartOptions = { responsive: true, scales: { xAxes: [{ type: 'time', stacked: false, time: { parser: 'MM/DD/YYYY HH:mm:ss', round: 'minute', tooltipFormat: 'LL HH:mm' }, scaleLabel: { display: true, labelString: 'Date' } }] } }; constructor(public api: APIService) { this.api.phoneEvent.subscribe(phones => { this.devices = phones.length; }); this.api.beatsEvent.subscribe(beats => { this.lineChartData[0].data = []; this.lineChartLabels = []; const batteryLevels: number[] = []; let currentLevel = 0; const finalBeats = beats.filter((val, i, array) => { if (currentLevel !== val.battery) { batteryLevels.push(val.battery); currentLevel = val.battery; return true; } else { return false; } }); finalBeats.forEach((beat) => { this.lineChartData[0].data.push(beat.battery); this.lineChartLabels.push(moment(new Date(beat.createdAt)).format(this.lineChartOptions.scales.xAxes[0].time.parser.toString())); }); let tDistance = 0; // Calculate distance for (let i = 0; i < beats.length; i++) { if (i >= beats.length || (i + 1) >= beats.length) { break; } const dist1 = beats[i].coordinate; const dist2 = beats[i + 1].coordinate; tDistance += this.api.distanceInKmBetweenEarthCoordinates(dist1[0], dist1[1], dist2[0], dist2[1]); i++; } this.totalDistance = tDistance.toFixed(2); }); } ngAfterViewInit(): void { } }