import {
  AdvancedProperty,
  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';

  @AdvancedProperty()
  public defaultFontFamily: string = ChartFontFamily.SANS_SERIF;
  @AdvancedProperty()
  public defaultFontWeight: string = '500';
  @AdvancedProperty()
  public defaultFontSize: number = 14;

  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];

    const fixRatio = window.devicePixelRatio;
    const textFontSize = () => {
      return fixRatio > 1 ? Math.round(this.defaultFontSize / fixRatio) : this.defaultFontSize;
    }

    args.meta.data.forEach((datapoint: any, i) => {
      ctx.font = ChartUtils.getFont({
                                      family: this.defaultFontFamily,
                                      weight: String(this.defaultFontWeight),
                                      size: textFontSize()
                                    });
      ctx.textAlign = 'center';
      ctx.fillStyle = this.useStaticColor ? this.color : datapoint.options.backgroundColor;
      ctx.fillText(this.getLabel(data, i), datapoint.x, datapoint.y - 6);
      ctx.restore();
    })
  }

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