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

88.63% Statements 234/264
75.59% Branches 96/127
83.33% Functions 35/42
88.37% Lines 228/258

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                                              91x                 125x     34x   34x 34x     34x 34x                                     34x 34x   34x       34x 34x   34x   34x 34x 34x 34x 34x   34x     34x 34x       34x   34x   34x 29x         34x 34x                                       91x 91x   91x   91x 3x   91x 3x     91x 91x 58x 7x       91x 34x   34x 34x 54x 28x   34x 34x 34x   34x   34x 34x 34x       34x   34x     34x   57x 28x 28x   28x                         68x 34x 34x     34x   34x 34x     34x             34x 34x 28x   45x 45x     44x       44x     44x 44x 28x     44x   44x   44x 28x     16x     44x                   6x   9x 9x 9x 9x 6x 6x   9x 4x   2x   2x       5x       8x       8x     8x 8x 2x     8x   8x   8x 2x     6x     8x                       52x 4x 4x     48x       48x 44x   4x 4x 2x 2x   2x     46x 46x 46x   107x   105x 56x     56x       56x 2x 2x   56x         98x 98x 98x 98x 98x 61x 61x 61x             61x 61x 61x 61x                 98x                                                                                                     1644x 1644x                                 98x   98x 98x     98x 58x                     98x                 52x 7x   52x 51x     1x       52x 52x       98x                                                                   150x 150x 150x 80x 128x 128x 26x   102x 102x 102x   102x 102x 8x     102x 102x   102x                 102x                 102x 102x 102x 102x 102x     102x 102x 100x       150x       64x 64x 64x   64x 64x   30x       64x 64x       54x 49x 49x     5x 3x       5x 3x               86x 86x         86x       86x 2x 2x   86x           2x   2x 2x                 1x   1x 1x                 2x 2x       100x                                                                 10x       45x   45x 45x 11x       45x 64x 64x 53x 53x 53x 53x 53x 53x 53x               3x        
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges } from '@angular/core';
import { TwinpadApiService } from '../../services/twinpad-api.service';
import { NumberSignalData, 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 { saveAs } from 'file-saver';
import { DatePipe, NgIf } from '@angular/common';
import { DurationPipe } from '../../pipes/duration.pipe';
 
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
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';
echarts.use([LineChart, GridComponent, CanvasRenderer, TitleComponent, ToolboxComponent, DataZoomComponent, LegendComponent]);
 
@Component({
    selector: 'app-signals-graph',
    imports: [FormsModule, NgxEchartsDirective, DatePipe, DurationPipe, ErrorComponent, NgIf, Drawer, ThemesComponent],
    providers: [provideEchartsCore({ echarts })],
    templateUrl: './signals-graph.component.html',
    styleUrl: './signals-graph.component.scss'
})
export class SignalsGraphComponent implements OnInit, OnChanges, OnDestroy{
 
  isLoading: boolean;
  error: HttpErrorResponse | null = null;
  @Input() signalIdsToPlot: string[];
  @Input() isLive: boolean=true;
  @Input() refreshTime: number=5;
  @Input() requestedWindowMinTs: number;
  @Input() requestedWindowMaxTs: number;
  @Input() liveWindow: number = 60;
  @Input() showLegend: boolean=true;
  @Input() refreshMode: string;
 
  signalsData: SignalsData;
  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;
 
  isYAxisScaling: boolean = true;
  updateYAxisScaling: 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() windowMiddleDate: EventEmitter<Date> = new EventEmitter();
  @Output() isResponseSlowerThanRefresh: EventEmitter<boolean> = new EventEmitter();
  @Output() hasFinishedDonwloading: EventEmitter<boolean> = new EventEmitter();
 
  constructor(private twinpadApiService: TwinpadApiService) {}
 
  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;
 
      if(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?
      if (this.dataMinTs !== undefined && this.dataMaxTs !== undefined){
        this.windowMinTs = this.windowStartValue;
        this.windowMaxTs = this.windowEndValue;
      }
      this.windowMiddleDate.emit(new Date(500*(this.windowMinTs+this.windowMaxTs)));
 
    });
  }
 
  ngOnChanges(changes: SimpleChanges): void {
    this.dataSubscription?.unsubscribe();
    this.firstSampleSubscription?.unsubscribe();
 
    this.firstSamples = undefined;
 
    if (this.requestedWindowMinTs !== undefined){
      this.windowMinTs = this.requestedWindowMinTs;
    }
    if (this.requestedWindowMaxTs !== undefined){
      this.windowMaxTs = this.requestedWindowMaxTs;
    }
 
    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();
        return this.twinpadApiService.getSignalValuesWithInterestWindow(this.signalIdsToPlot, this.windowMinTs);
      }, 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();
            }
 
            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();
        if (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 {
          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();
            }
 
            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(): any{ // eslint-disable-line
    const series: LineSeriesOption[] = [];
    const legend: string[] = [];
    const legendSelection: { [id: string]: boolean } = {};
    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
    };
 
    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[] = [];
    const signalsData = this.signalsData.copy(); // Copy to avoid concurrent update
    if (signalsData.signals_data !== undefined && signalsData.signals_data.length > 0){
      for (let isignal = 0; isignal < this.signalIdsToPlot.length; isignal++){
        const signalData: StringSignalData|NumberSignalData = signalsData.signals_data[isignal];
        if (signalData === undefined) {
          continue;
        }
        const [data, forced_data] = signalData.echartsSerieData();
        Eif (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 = this.signalIdsToPlot[isignal];
        const signalThemeToApply = this.signalsGraphThemes.get(signalId);
 
        const valueOptions: LineSeriesOption = {
          name: signalId,
          type: 'line',
          smooth: false,
          symbol: 'none',
          yAxisIndex: yAxisIndex,
          data: data,
        };
 
        const forcedValueOptions: LineSeriesOption = {
          name: signalId + " forced value",
          type: 'line',
          smooth: false,
          symbol: 'none',
          yAxisIndex: yAxisIndex,
          data: forced_data,
        };
 
        Eif (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(this.signalIdsToPlot[isignal])) {
          series.push(forcedValueOptions);
        }
      }
    }
    return series;
  }
 
  updateGraphForce(){
    this.isLoading = true;
    const series = this.computeSeries();
    this.options = this.generateOptions();
 
    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.windowMinTs === undefined){
        Iif (this.requestedWindowMinTs !== undefined){
          this.windowMinTs = this.requestedWindowMinTs;
        }
      }
      if (this.windowMaxTs === undefined){
        Iif (this.requestedWindowMaxTs !== undefined){
          this.windowMaxTs = this.requestedWindowMaxTs;
        }
      }
    }
  }
 
  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);
        saveAs(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);
        saveAs(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;
  }
 
  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();
  }
 
}