import {
  AnalyticalScope,
  Behavior,
  ChartFontFamily, ColorEditor, NotNull,
  Visible
} from "@webbpm/base-package";
import {ChartPlugin} from "./ChartPlugin";
import {Chart, ChartMeta} from "chart.js";
import {ErvuChartV2} from "../ErvuChartV2";
import {ChartUtils} from "../ChartUtils";

@AnalyticalScope(ErvuChartV2)
export class BarDataLabelChartPlugin extends Behavior implements ChartPlugin {
  @Visible('false')
  id: string = 'barDataLabel';

  public labelAxis = 'y';

  public weight: number = 500;
  public size: number = 12;
  public family: ChartFontFamily = ChartFontFamily.SANS_SERIF;

  public useStaticColor: boolean = true;
  @Visible('useStaticColor == true')
  @NotNull('useStaticColor == true')
  @ColorEditor()
  public color: string;

  afterDatasetDraw(chart: Chart, args: { index: number; meta: ChartMeta }): void {
    let ctx = chart.ctx;
    let data = chart.data.datasets[args.index];
    args.meta.data.forEach((datapoint: any, i) => {
      ctx.font = ChartUtils.getFont({
                                      family: this.family,
                                      weight: String(this.weight),
                                      size: this.size
                                    });
      ctx.textAlign = 'center';
      ctx.fillStyle = this.useStaticColor ? this.color : datapoint.options.backgroundColor;
      ctx.fillText(this.getLabel(data, i), datapoint.x, datapoint.y - 6);
    })
  }

  private getLabel(data: any, index: number): string {
    let point = data.data[index];
    return typeof point == 'object' ? point[this.labelAxis] : point;
  }
}