import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnChanges,
  SimpleChanges
} from '@angular/core';
import {Visible} from "@webbpm/base-package";
import {TooltipModel} from "chart.js";

@Component({
             moduleId: module.id,
             selector: 'ervu-chart-tooltip',
             templateUrl: `./../../../../../src/resources/template/ervu-dashboard/ErvuChartTooltip.html`,
             changeDetection: ChangeDetectionStrategy.OnPush
           })
export class ErvuChartTooltip implements OnChanges {
  @Input()
  public tooltipModel: TooltipModel<any>;
  @Input()
  public position: any;

  @Visible("false")
  public visible: boolean = false;
  @Visible("false")
  public items: any[];

  ngOnChanges(changes: SimpleChanges): void {
    if ('position' in changes) {
      if (!this.tooltipModel || this.tooltipModel.opacity == 0 || this.tooltipModel.body.length == 0) {
        this.visible = false;
        return;
      }
      this.visible = true;
      this.refreshContent();
    }
  }

  public refreshContent() {
    const tooltipModel: TooltipModel<any> = this.tooltipModel;
    const titleLines: string[] = tooltipModel.title || [];
    const bodyLines: any = tooltipModel.body.map((bodyItem) => bodyItem.lines);

    this.items = bodyLines.map((body, i) => ({
      title: titleLines[i] || '',
      body: body,
      color: this.tooltipModel.labelColors[i].backgroundColor
    }));
  }
}
