import { ChartType, IDataset } from './chart-type';

interface IOptions {
  colors: string[];
  fills: string[];
  fillAlpha: number;
}

interface IChart {
  config: { type: ChartType };
  ctx: CanvasRenderingContext2D;
  data: { datasets: IDataset[] };
}

export class PluginMoreColors {
  static config() {
    return {
      id: 'morecolors',
      beforeUpdate: function (chart: IChart, args: any, options: IOptions) {
        const { datasets } = chart?.data ?? { datasets: [] };
        const { colors, fills, fillAlpha } = options;
        const c_length = colors?.length ?? 0;
        const f_length = fills?.length ?? 0;

        if (c_length === 0) return;

        datasets.forEach((dataset: IDataset, index: number) => {
          const color = colors[index % c_length];
          const fill = f_length > 0 ? fills[index % f_length] : undefined;

          switch (dataset.type ?? chart?.config?.type) {
            case ChartType.Line:
            case ChartType.Radar:
            case ChartType.Scatter:
              // line connecting points
              dataset.borderColor = dataset.borderColor ?? color;
              if (fill)
                dataset.backgroundColor = dataset.backgroundColor ?? fill;
              // points
              dataset.pointBorderColor = dataset.pointBorderColor ?? color;
              if (fill)
                dataset.pointBackgroundColor =
                  dataset.pointBackgroundColor ?? fill;
              break;
            case ChartType.Doughnut:
            case ChartType.Pie:
            case ChartType.PolarArea:
              const current = dataset.backgroundColor ?? [];
              dataset.backgroundColor = (dataset.data ?? []).map(
                (_, index: number) => current[index] ?? colors[index % length]
              );
              break;
            case ChartType.Bar:
              dataset.borderColor = dataset.borderColor ?? color;
              if (fill)
                dataset.backgroundColor = dataset.backgroundColor ?? fill;
              break;
            default:
              dataset.borderColor = dataset.borderColor ?? color;
              if (fill)
                dataset.backgroundColor = dataset.backgroundColor ?? fill;
              break;
          }
        });
      },
      defaults: {
        colors: [],
        fills: [],
        fillAlpha: 1.0,
      } as IOptions,
    };
  }
}
