All files / src/app/components/signals-graph signals-graph.component.ts

89.38% Statements 278/311
78.06% Branches 121/155
82.97% Functions 39/47
89.4% Lines 270/302

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790                                                108x                 155x 47x     47x   47x 47x     47x 47x   47x   47x                             47x       47x 47x 47x   47x       47x 47x   47x   47x 47x 47x 47x 47x 47x     47x 47x       47x   47x   47x 40x         47x 47x 1x   1x 1x 1x 1x       1x 1x 1x     1x   1x 1x 1x         114x 49x 49x 14x 14x 14x 14x   49x   65x                     65x 65x   65x   65x 65x 33x 7x       65x 31x   31x 31x 51x 24x   31x 31x 31x   31x   31x 31x 31x       31x   31x     31x   34x 28x 28x   28x                         78x 40x 40x     38x   38x 38x     38x             38x 38x 32x   54x   54x 54x 34x   54x     54x       54x     54x 54x 49x     54x   54x   54x 49x     5x     54x 54x 54x                 6x   10x 10x 10x 10x 10x 10x   10x 4x   2x   2x       6x                       6x       10x       10x     10x 10x 3x     10x   10x   10x 3x     7x     10x 10x 10x                       80x 22x 22x     58x       58x 54x   4x 4x 2x 2x   2x     56x 56x 56x   105x   103x 57x     57x       57x 2x 2x   57x         151x 151x 151x 151x 73x 73x 73x             73x 73x 73x             151x 139x 139x 87x 87x 87x             87x 87x 87x 87x                   151x                                                                                                     1754x 1754x                                 151x 560x 24x     151x   151x 151x     151x 80x                     151x                 64x 9x   64x 63x     1x       64x 64x       151x                                                                   224x 284x 284x     284x 284x 122x   284x 284x 30x     284x 284x   284x                   284x                   284x 102x 102x 102x 102x     284x 284x 98x     224x       104x 104x 104x   104x 104x   64x       104x 104x       64x 58x 58x     6x 3x 3x   6x 2x   6x 2x           120x 120x         120x       120x 2x 2x   120x           2x   2x 2x                 1x   1x 1x                 2x 2x       153x                                                                 10x       2x       42x   42x 42x 12x       42x 61x 61x 49x 49x 49x 49x 49x 49x 49x               5x 108x      
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, inject } from '@angular/core';
import { TwinpadApiService } from '../../services/twinpad-api.service';
import { DurationOption, SignalSample, SignalsData, StringSignalData } from '../../models/signals';
 
import { FormsModule } from '@angular/forms';
 
import type { DataZoomComponentOption, EChartsOption, LineSeriesOption } from 'echarts';
 
import { NgxEchartsDirective, provideEchartsCore } from 'ngx-echarts';
import * as echarts from 'echarts/core';
import { Subscription } from 'rxjs';
import { DatePipe } from '@angular/common';
import { DurationPipe, ShortDurationPipe } from '../../pipes/duration.pipe';
 
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { XAXisOption } from 'echarts/types/dist/shared';
import { GridComponent, TitleComponent, ToolboxComponent, DataZoomComponent, LegendComponent } from 'echarts/components';
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorComponent } from '../error/error.component';
import { LineStyle, SignalAppearance } from '../../models/colorSetting';
import { ThemesComponent } from '../themes/themes.component';
import { Drawer } from 'primeng/drawer';
import { saveFile } from '../../utils/utils';
echarts.use([LineChart, GridComponent, CanvasRenderer, TitleComponent, ToolboxComponent, DataZoomComponent, LegendComponent]);
 
@Component({
    selector: 'app-signals-graph',
    imports: [FormsModule, NgxEchartsDirective, DatePipe, DurationPipe, ErrorComponent, Drawer, ThemesComponent],
    providers: [provideEchartsCore({ echarts })],
    templateUrl: './signals-graph.component.html',
    styleUrl: './signals-graph.component.scss'
})
export class SignalsGraphComponent implements OnInit, OnChanges, OnDestroy{
  private twinpadApiService = inject(TwinpadApiService);
 
  isLoading: boolean;
  error: HttpErrorResponse | null = null;
  @Input() signalIdsToPlot: string[];
  @Input() isLive: boolean=true;
  @Input() refreshTime: number=5;
  @Input() replayWindowMiddle: Date;
  @Input() replayWindowLength: DurationOption;
  @Input() liveWindow: number = 60;
  @Input() showLegend: boolean=true;
  @Input() refreshMode: string;
  @Input() relativeMode: boolean = false;
 
  signalsData: SignalsData = new SignalsData([], null, null);
  options: EChartsOption;
  updateOptions: EChartsOption;
  dataSubscription: Subscription;
  firstSampleSubscription: Subscription;
  private chart!: echarts.ECharts;
 
  windowMinTs: number;
  windowMaxTs: number;
  windowStartValue: number;
  windowEndValue: number;
  dataMinTs: number;
  dataMaxTs: number;
  liveMinTs: number;
  lastGraphRefreshTs: number;
  windowChanged: boolean = true;
  windowChangeTimestamp: number;
  currentRequestTimeout: NodeJS.Timeout;
 
  isYAxisScaling: boolean = true;
  updateYAxisScaling: boolean = false;
  displayPoints: boolean = false;
 
  labels: string[] = [];
  firstSamples: SignalSample[] | undefined;
 
  signalsForcibilities: Map<string, boolean>;
  signalsGraphThemes: Map<string, SignalAppearance> = new Map();
  defaultGraphColors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
 
  displayThemeBuilder: boolean = false;
 
  @Output() dataDateMin: EventEmitter<Date> = new EventEmitter();
  @Output() dataDateMax: EventEmitter<Date> = new EventEmitter();
  @Output() replayWindowMiddleChange = new EventEmitter<Date>();
  @Output() replayWindowLengthChange = new EventEmitter<DurationOption>();
  @Output() isResponseSlowerThanRefresh: EventEmitter<boolean> = new EventEmitter();
  @Output() hasFinishedDonwloading: EventEmitter<boolean> = new EventEmitter();
 
  ngOnInit() {
    this.isLoading = true;
    this.signalsForcibilities = new Map();
 
    // First, fetch signals data type to configure Str Y Axis
 
    this.options = this.generateOptions();
 
    this.updateData();
 
    if (this.signalIdsToPlot.length == 0){
      this.isLoading = false;
    }
  }
 
  onChartInit(ec: echarts.ECharts) {
    this.chart = ec;
    this.chart.on('dataZoom', (_: any) => { // eslint-disable-line
      const option = this.chart.getOption() as EChartsOption;
 
      Eif(option !== undefined && option.dataZoom !== undefined) {
        const dataZoom = option.dataZoom as DataZoomComponentOption[];
        this.windowStartValue = dataZoom[0]['startValue'] as number;
        this.windowEndValue = dataZoom[0]['endValue'] as number;
      }
 
      // Move this to window update?
      Eif (this.dataMinTs !== undefined && this.dataMaxTs !== undefined){
        this.windowMinTs = this.windowStartValue;
        this.windowMaxTs = this.windowEndValue;
      }
 
      this.replayWindowMiddleChange.emit(new Date(500 * (this.windowStartValue + this.windowEndValue)));
 
      const durationPipe = new ShortDurationPipe();
      const windowLength = this.windowMaxTs - this.windowMinTs;
      this.replayWindowLengthChange.emit({label: durationPipe.transform(windowLength), duration: windowLength});
    });
  }
 
  ngOnChanges(changes: SimpleChanges): void {
    if ("replayWindowMiddle" in changes) {
      this.replayWindowMiddle = changes["replayWindowMiddle"]["currentValue"];
      if (!this.isLive && this.replayWindowMiddle !== undefined && this.replayWindowLength !== undefined) {
        this.windowMinTs = (this.replayWindowMiddle.valueOf() / 1000) - this.replayWindowLength.duration / 2;
        this.windowMaxTs = (this.replayWindowMiddle.valueOf() / 1000) + this.replayWindowLength.duration / 2;
        this.windowChanged = true;
        this.windowChangeTimestamp = Date.now();
      }
      return;
    }
    Iif ("replayWindowLength" in changes) {
      this.replayWindowLength = changes["replayWindowLength"]["currentValue"];
      if (!this.isLive && this.replayWindowMiddle !== undefined && this.replayWindowLength !== undefined) {
        this.windowMinTs = (this.replayWindowMiddle.valueOf() / 1000) - this.replayWindowLength.duration / 2;
        this.windowMaxTs = (this.replayWindowMiddle.valueOf() / 1000) + this.replayWindowLength.duration / 2;
        this.windowChanged = true;
        this.windowChangeTimestamp = Date.now();
      }
      return;
    }
 
    this.dataSubscription?.unsubscribe();
    this.firstSampleSubscription?.unsubscribe();
 
    this.firstSamples = undefined;
 
    let shouldUpdateData = true;
    if ("isLive" in changes){
      if (changes["isLive"]["currentValue"] === false){
        shouldUpdateData = false;
      }
    }
 
    if (this.signalIdsToPlot?.length > 0) {
      this.twinpadApiService.getSignals(0, 0, null, null, this.signalIdsToPlot).subscribe(
        signalsData => {
          const labels = new Set<string>();
          for (const signal of signalsData.items){
            for (const enumOption of signal.stringEnumOptions())
              labels.add(enumOption);
          }
          const newLabels = Array.from(labels);
          Eif (this.labels != newLabels){
            shouldUpdateData = true;
          }
          this.labels = newLabels;
 
          Eif (shouldUpdateData){
            this.isLoading = true;
            this.updateData();
          }
        }
      );
      this.twinpadApiService.getSignalsForcibility(this.signalIdsToPlot).subscribe({
        next: forcibilities => {
          this.signalsForcibilities = forcibilities;
        }
      });
      this.updateGraphThemes();
    }
    else if (this.options !== undefined) {
      this.options.legend = {};
      this.options.series = [];
 
      Iif (this.chart){
        // Pass changes through options updates
        this.chart.setOption(this.options, true);
      }
    }
  }
 
    /**
   * fetch signalData drom signals to plot and trigger graph update
   * Make the api subscription
   */
  updateData() {
 
    if (this.signalIdsToPlot === undefined || this.signalIdsToPlot.length === 0 || this.signalsData === undefined) {
      this.signalsData = new SignalsData([], null, null);
      this.updateGraphForce();
    }
    else {
      this.firstSampleSubscription?.unsubscribe();
 
      this.twinpadApiService.getSignalFirstValues(this.signalIdsToPlot).subscribe(value => {
        this.firstSamples = value;
      });
 
      this.subscribeData();
 
 
    }
  }
 
  subscribeData(initialDelay?:number){
    this.dataSubscription?.unsubscribe();
    if (this.refreshMode === "Single-point" && this.isLive) {
      this.dataSubscription = this.twinpadApiService.callPeriodically(
      () => {
        this.updateWindowBounds();
        // To avoid very long interest windows (ie. 1 hour), only fecth points later than what we already have
        let minLatestTimestamp = Math.min(...this.signalsData.signals_data.map(sd => sd.time_vector[sd.time_vector.length - 1] ?? 0));
        if (minLatestTimestamp === Infinity || Number.isNaN(minLatestTimestamp)) {
          minLatestTimestamp = 0;
        }
        return this.twinpadApiService.getSignalValues(this.signalIdsToPlot);
      }, 1000 * this.refreshTime, initialDelay).subscribe({
          next: (value) => {
            this.error = null;
 
            // check if data request time is longer than refresh time
            // subscribe happens every 1000*refreshTime, so time spent requesting data = difference_between_two_timings - refresh time
            this.isResponseSlowerThanRefresh.emit(Date.now() - (this.lastGraphRefreshTs + this.refreshTime * 1000) > this.refreshTime * 1000);
 
            // Data return callback
            let shouldForce = false;
            if (this.signalsData === undefined || this.signalsData.signals_data === undefined || this.signalsData.signals_data.length !== value?.length) {
              shouldForce = true;
            }
 
            this.updateSignalsData(value);
 
            this.updateDataTimestampBoundaries();
 
            if (shouldForce) {
              this.updateGraphForce();
            }
            else {
              this.updateGraph();
            }
 
            clearTimeout(this.currentRequestTimeout);
            this.isLoading = false;
            this.lastGraphRefreshTs = Date.now();
          },
          error: (error) => {
            this.error = error;
            this.subscribeData(2000);
          }
      });
    }
    else {
      this.dataSubscription = this.twinpadApiService.callPeriodically(
      () => {
        let tsMin = null;
        let tsMax = null;
        this.updateWindowBounds();
        Eif (this.windowMinTs !== undefined && this.windowMaxTs !== undefined) {
          tsMax = this.windowMaxTs + 5;
          tsMin = this.windowMinTs - 5;
        }
        if (this.isLive) {
          switch (this.refreshMode) {
            case "Latest points":
              return this.twinpadApiService.getSignalsData(this.signalIdsToPlot, 100, this.windowMaxTs - this.refreshTime, this.windowMaxTs, false);
            default:
              return this.twinpadApiService.getSignalsData(this.signalIdsToPlot, 800, this.windowMinTs, this.windowMaxTs, true);
          }
        }
        else {
          this.currentRequestTimeout = setTimeout(
            () => {
              this.isResponseSlowerThanRefresh.emit(true);
              if (this.windowChanged) {
                this.isLoading = true;
              }
              if (this.windowChangeTimestamp < this.lastGraphRefreshTs) {
                this.windowChanged = false;
              }
            },
            this.refreshTime * 1000
          );
          return this.twinpadApiService.getSignalsDataWithInterestWindow(this.signalIdsToPlot, 800, 200, this.windowMinTs, this.windowMaxTs, tsMin, tsMax);
        }
      }, 1000 * this.refreshTime, initialDelay).subscribe({
          next: (value) => {
            this.error = null;
 
            // check if data request time is longer than refresh time
            // subscribe happens every 1000*refreshTime, so time spent requesting data = difference_between_two_timings - refresh time
            this.isResponseSlowerThanRefresh.emit(Date.now() - (this.lastGraphRefreshTs + this.refreshTime * 1000) > this.refreshTime * 1000);
 
            // Data return callback
            let shouldForce = false;
            if (this.signalsData === undefined || this.signalsData.signals_data === undefined || this.signalsData?.signals_data.length != value?.signals_data.length) {
              shouldForce = true;
            }
 
            this.updateSignalsData(value);
 
            this.updateDataTimestampBoundaries();
 
            if (shouldForce) {
              this.updateGraphForce();
            }
            else {
              this.updateGraph();
            }
 
            clearTimeout(this.currentRequestTimeout);
            this.isLoading = false;
            this.lastGraphRefreshTs = Date.now();
          },
          error: (error) => {
            this.error = error;
            this.subscribeData(2000);
 
          }
      });
    }
  }
 
  updateSignalsData(newBatch: SignalsData | SignalSample[]) {
    if (!this.isLive) {
      this.signalsData = newBatch as SignalsData;
      return;
    }
 
    Iif (this.signalsData === undefined) {
      this.signalsData = new SignalsData([], null, null);
    }
 
    if ((<SignalSample[]>newBatch)?.length !== undefined) {
      this.signalsData.push(newBatch as SignalSample[]);
    }
    else Eif (newBatch !== undefined) {
      if (this.refreshMode === "Full window") {
        this.signalsData = newBatch as SignalsData;
        return;
      }
      this.signalsData.concat(newBatch as SignalsData);
    }
 
    const delayMargin = 0.1;
    this.signalsData.pruneDeselectedSignals(this.signalIdsToPlot);
    for (const signalData of this.signalsData.signals_data) {
      // remove outdated points with a delay margin
      signalData.time_vector = signalData.time_vector.filter(ts => ts >= this.windowMinTs - delayMargin);
      // count number of points off to the left of the graph and replace them by one point right on the edge
      const numberInvisiblePoints = signalData.time_vector.filter(ts => ts < this.windowMinTs).length;
      for (let i = 0; i < numberInvisiblePoints; i++) {
        signalData.time_vector.shift();
      }
      Iif (numberInvisiblePoints > 0) {
        signalData.time_vector.unshift(this.windowMinTs);
      }
      // adjust to the new length after having removed values
      while (signalData.values.length > signalData.time_vector.length) {
        signalData.values.shift();
        signalData.forced_values.shift();
      }
      signalData.number_samples = signalData.time_vector.length;
    }
  }
 
  generateOptions(customLegend: [string, string][] = []): any{ // eslint-disable-line
    const series: LineSeriesOption[] = [];
    const legend: string[] = [];
    const legendSelection: { [id: string]: boolean } = {};
    for (const [valueLegend, forcedValueLegend] of customLegend) {
      legend.push(valueLegend);
      legendSelection[valueLegend] = true;
      series.push({
        name: valueLegend,
        type: 'line',
        smooth: false,
        symbol: 'none',
        data: []});
 
      legend.push(forcedValueLegend);
      legendSelection[forcedValueLegend] = false;
      series.push({
        name: forcedValueLegend,
        type: 'line',
        smooth: false,
        symbol: 'none',
        data: []});
    }
    if (legend.length === 0) {
      Eif(this.signalIdsToPlot !== undefined){
        for (const signalId of this.signalIdsToPlot){
          legend.push(signalId);
          legendSelection[signalId] = true;
          series.push({
            name: signalId,
            type: 'line',
            smooth: false,
            symbol: 'none',
            data: []});
 
          const forcedValueName = signalId + ' forced value';
          legend.push(forcedValueName);
          legendSelection[forcedValueName] = false;
          series.push({
            name: forcedValueName,
            type: 'line',
            smooth: false,
            symbol: 'none',
            data: []});
        }
      }
    }
 
    const options: EChartsOption = {
      animation: false,
      grid: {
        left: 0,
        right: 60,
        top: 40,
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          axis: 'x',
          snap: true,
        },
        valueFormatter: function(value) {
          const tooltipValue = value?.toString() ?? "0";
          // it received a timestamp:
          if (!Number.isNaN(tooltipValue) && Date.now() / 1000 - +(tooltipValue) < 86400) {
            const date = +(tooltipValue) * 1000;
            const datepipe = new DatePipe("en-US");
            return datepipe.transform(date, "HH:mm:ss.SSS") ?? "";
          }
          return tooltipValue;
        }
      },
      toolbox: {
        show: false,
        feature: {
          dataZoom: {
            yAxisIndex: 'none'
          },
          restore: {},
          saveAsImage: {name: 'twinpad_signals'}
        }
      },
      xAxis: {
        type: 'value',
        minorTick: {
          show: true
        },
        splitLine: {
          show: true,
          lineStyle: {type: 'solid', width:0.3}
        },
        minorSplitLine: {
          show: true,
          lineStyle: {type: 'dashed', width:0.3}
        },
        axisLabel: {
          formatter: function(value){
            const datepipe = new DatePipe("en-US");
            return datepipe.transform(value * 1000, "yyyy/MM/dd - HH:mm:ss") ?? `${value}`;
          }
        },
        axisPointer: {
          label: {
            formatter: function(params) {
              const value = +params.value.toString() * 1000;
              const datepipe = new DatePipe("en-US");
              return datepipe.transform(value, "yyyy/MM/dd - HH:mm:ss.SSS") ?? `${params.value}`;
            }
          }
        }
      },
      dataZoom: this.computeDataZoom(),
      series: series
    };
 
    if (this.relativeMode) {
      (options.xAxis as XAXisOption).axisLabel = { formatter: function(value: number) { return value.toString(); }};
      (options.xAxis as XAXisOption).axisPointer = { label: { formatter: function(params) { return params.value.toString(); } } };
    }
 
    this.updateYAxis(options);
 
    Eif (this.showLegend){
      options.legend = {data: legend, selectedMode: "multiple", type: 'scroll', selected: legendSelection};
    }
 
    if (this.signalIdsToPlot === undefined || this.signalIdsToPlot.length == 0){
      options.title = {
        text: 'No signal selected',
        textAlign: 'center',
        left: '50%',
        top: '40%',
        textStyle: {
          fontSize: 30
        }
      };
    }
 
    return options;
  }
 
  /**
   * Update dataMinTs and dataMaxTs according to signal data
   * also update windowMinTs and xMaxTs from component input (requested)
   */
  updateDataTimestampBoundaries(){
 
    if (this.signalsData.data_start !== null){
      this.dataMinTs = this.signalsData.data_start;
    }
    if (this.signalsData.data_end !== null){
      this.dataMaxTs = this.signalsData.data_end;
    }
    else{
      this.dataMaxTs = Date.now() * 0.001;
    }
 
    // Emitting new dates
    this.dataDateMin.emit(new Date(1000*this.dataMinTs));
    this.dataDateMax.emit(new Date(1000*this.dataMaxTs));
  }
 
  computeDataZoom(){
    return [
      {
        type: 'slider',
        start: 0,
        end: 100,
        xAxisIndex: 0,
        zoomOnMouseWheel: false,
        show: false
      },
      {
        type: 'inside',
        start: 0,
        end: 100,
        xAxisIndex: 0,
        zoomOnMouseWheel: false,
      },
      {
        type: 'slider',
        start: 0,
        end: 100,
        yAxisIndex: 0,
        zoomOnMouseWheel: false
      },
      {
        type: 'inside',
        start: 0,
        end: 100,
        yAxisIndex: 0,
        zoomOnMouseWheel: false
      }
    ];
  }
 
  computeSeries(): LineSeriesOption[]{
    const series: LineSeriesOption[] = [];
    for (const [iSignal, signalData] of this.signalsData.signals_data.map((value, index) => [index, value] as const)) {
      Iif (signalData === undefined) {
        continue;
      }
      const [data, forced_data] = signalData.echartsSerieData();
      if (this.firstSamples !== undefined){
        data.unshift([1000*this.firstSamples[iSignal].timestamp, this.firstSamples[iSignal].value]);
      }
      let yAxisIndex: number = 0;
      if (signalData instanceof StringSignalData){
        yAxisIndex = 1;
      }
 
      const signalId = signalData.signal_id;
      const signalThemeToApply = this.signalsGraphThemes.get(signalId);
 
      const valueOptions: LineSeriesOption = {
        name: signalData.customName ?? signalId,
        type: 'line',
        smooth: false,
        symbol: this.displayPoints ? 'circle' : 'none',
        symbolSize: 7,
        yAxisIndex: yAxisIndex,
        data: data,
      };
 
      const forcedValueOptions: LineSeriesOption = {
        name: signalData.customForcedName ?? signalId + " forced value",
        type: 'line',
        smooth: false,
        symbol: this.displayPoints ? 'circle' : 'none',
        symbolSize: 7,
        yAxisIndex: yAxisIndex,
        data: forced_data,
      };
 
      if (signalThemeToApply !== undefined) {
        valueOptions.itemStyle = { color: signalThemeToApply.value_color };
        valueOptions.lineStyle = { color: signalThemeToApply.value_color, type: signalThemeToApply.value_line_style };
        forcedValueOptions.itemStyle = { color: signalThemeToApply.forced_value_color };
        forcedValueOptions.lineStyle = { color: signalThemeToApply.forced_value_color, type: signalThemeToApply.forced_value_line_style };
      }
 
      series.push(valueOptions);
      if (this.signalsForcibilities.get(signalId)) {
        series.push(forcedValueOptions);
      }
    }
    return series;
  }
 
  updateGraphForce(customLegend: [string, string][] = []){
    this.isLoading = true;
    const series = this.computeSeries();
    this.options = this.generateOptions(customLegend);
 
    this.options.series = series;
    if (this.chart){
        // Pass changes through options updates
        this.chart.setOption(this.options, true);
    }
 
    // Force update: a bit ugly but works
    this.updateGraph();
    this.isLoading = false;
  }
 
  updateWindowBounds(){
    if (this.isLive){
      this.windowMaxTs = Date.now()/1000;
      this.windowMinTs = this.windowMaxTs - this.liveWindow;
    }
    else{
      if (this.replayWindowMiddle === undefined) {
        this.replayWindowMiddle = new Date(Date.now() - this.replayWindowLength.duration * 1000 / 2);
        this.replayWindowMiddleChange.emit(this.replayWindowMiddle);
      }
      if (this.windowMinTs === undefined){
        this.windowMinTs = (this.replayWindowMiddle.valueOf() / 1000) - this.replayWindowLength.duration / 2;
      }
      if (this.windowMaxTs === undefined){
        this.windowMaxTs = (this.replayWindowMiddle.valueOf() / 1000) + this.replayWindowLength.duration / 2;
      }
    }
  }
 
  updateGraph(){
    const series = this.computeSeries();
    const dataZoom = [
      {type: "slider", startValue: this.windowMinTs, endValue: this.windowMaxTs, zoomOnMouseWheel:!this.isLive, zoomLock:this.isLive, disabled:this.isLive},
      {type: "inside", startValue: this.windowMinTs, endValue: this.windowMaxTs, zoomOnMouseWheel:!this.isLive, zoomLock:this.isLive, disabled:this.isLive}
    ];
 
    this.updateOptions = {
      dataZoom: dataZoom,
      series: series,
    };
    if (this.updateYAxisScaling) {
      this.updateYAxis(this.updateOptions);
      this.updateYAxisScaling = false;
    }
    this.isLoading = false;
  }
 
 
 
  downloadSignalsZip(format: string){
    this.twinpadApiService.downloadSignalsDataZip(format, this.signalIdsToPlot, this.windowMinTs, this.windowMaxTs).subscribe({
      next: blob  => {
        this.hasFinishedDonwloading.emit(true);
        saveFile(document, blob, `signals-data_${format}.zip`);
      },
      error: error => {
        console.error('Error downloading the blob', error);
      }
    });
  }
 
  downloadSignalsHDF5(){
    this.twinpadApiService.downloadSignalsDataHDF5(this.signalIdsToPlot, this.windowMinTs, this.windowMaxTs).subscribe({
      next: blob => {
        this.hasFinishedDonwloading.emit(true);
        saveFile(document, blob, 'signals-data.hdf5');
      },
      error: error => {
        console.error('Error downloading the blob', error);
      }
    });
  }
 
  toggleYAxisScaling() {
    this.isYAxisScaling = !this.isYAxisScaling;
    this.updateYAxisScaling = true;
  }
 
  updateYAxis(options: EChartsOption) {
    options.yAxis = [
        {
        type: 'value',
        id: "0",
        show: true,
        splitNumber: 10,
        position: 'right',
        minorTick: {
          show: true
        },
        splitLine: {
          show: true,
          lineStyle: {type: 'solid', width:0.3}
        },
        minorSplitLine: {
          show: false,
          lineStyle: {type: 'dashed', width:0.3}
        },
        scale: this.isYAxisScaling,
        boundaryGap: ['5%', '5%']
      },
      {
        type: 'category',
        show: this.labels.length>0, //begin without
        axisTick: {"alignWithLabel": true},
        id: "1",
        position: 'left',
        data: this.labels,
      }
    ];
  }
 
  toggleThemeBuilder() {
    this.displayThemeBuilder = !this.displayThemeBuilder;
  }
 
  togglePoints() {
    this.displayPoints = !this.displayPoints;
  }
 
  updateGraphThemes() {
    this.twinpadApiService.getSignalsGraphThemes(this.signalIdsToPlot).subscribe({
      next: graphThemes => {
        this.signalsGraphThemes.clear();
        for (const [key, value] of Object.entries(graphThemes)) {
          this.signalsGraphThemes.set(key, value);
        }
        // When disabling a theme, the line styles are not set back to default values
        // To fix this, we take the default colors from echarts and set them for the signals
        for (let i = 0; i < this.signalIdsToPlot.length; i++) {
          const signalId = this.signalIdsToPlot[i];
          if (this.signalsGraphThemes.get(signalId) === undefined) {
            const signalNumber = i * 2;
            const defaultTheme = new SignalAppearance();
            defaultTheme.value_color = this.defaultGraphColors[signalNumber % this.defaultGraphColors.length];
            defaultTheme.forced_value_color = this.defaultGraphColors[(signalNumber + 1) % this.defaultGraphColors.length];
            defaultTheme.value_line_style = LineStyle.solid;
            defaultTheme.forced_value_line_style = LineStyle.solid;
            this.signalsGraphThemes.set(signalId, defaultTheme);
          }
        }
      }
    });
  }
 
  ngOnDestroy() {
    this.dataSubscription?.unsubscribe();
  }
 
}