/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import { Widget, WidgetContentComponent } from '@bci-web-core/pinboard';
import {Chart, ChartConfiguration} from 'chart.js/auto';

export class ChartjsWidgetSetting {
  public chartjsConf: ChartConfiguration;
}

@Component({
  selector: 'bci-chartjs-content',
  templateUrl: './chartjs-content.component.html',
  styleUrls: ['./chartjs-content.component.scss'],
})
export class ChartjsContentComponent implements WidgetContentComponent, AfterViewInit {
  @ViewChild('chartContainer', { static: true }) public chartContainer: ElementRef;
  public chart: Chart = null;
  private _widget: Widget<ChartjsContentComponent, any, ChartjsWidgetSetting>;

  get widget(): Widget<ChartjsContentComponent, any, ChartjsWidgetSetting> {
    return this._widget;
  }

  set widget(widget: Widget<ChartjsContentComponent, any, ChartjsWidgetSetting>) {
    this._widget = widget;
  }

  public chartIsConfigured = false;

  ngAfterViewInit(): void {
    const config = this.getchartjsConfig();
    if (config) {
      this.chart = new Chart(this.chartContainer.nativeElement, config);
    }
  }

  public resize(): void {
    this.chart.resize();
  }

  /**
   * Destroys old chart, creates new Chart with widget's config
   */
  public update(resizeAfter?: boolean): void {
    const config = this.getchartjsConfig();
    if (this.chart !== null) {
      this.chart.destroy();
    }
    this.chart = new Chart(this.chartContainer.nativeElement, config);
    this.chartIsConfigured = !!this.widget.settings.chartjsConf;

    if (resizeAfter) {
      this.resize();
    }
  }

  private getchartjsConfig(): ChartConfiguration {
    return this.widget.settings.chartjsConf;
  }
}
