import { Injectable } from '@angular/core';
import { ChartConfig } from '../chart-config';
import { ChartAxis, ChartAxisPosition, IDataset } from '../chart-type';

@Injectable()
export class DatasetService {
  constructor() {}

  datasets(chart: ChartConfig, data: Record<string, any>[]): IDataset[] {
    const result: IDataset[] = [];

    (chart?.axis ?? []).forEach((axis: ChartAxis) => {
      switch (axis.position) {
        case ChartAxisPosition.Left:
        case ChartAxisPosition.Right:
          const ds = this.dataset(axis, data);
          result.push(...ds);
          break;
      }
    });

    return result;
  }

  private dataset(axis: ChartAxis, data: Record<string, any>[]): IDataset[] {
    let result: IDataset[] = [];

    const labels = Array.isArray(axis.label) ? axis.label : [axis.label];
    const sources = Array.isArray(axis.source) ? axis.source : [axis.source];

    if (labels.length !== sources.length) return result;

    labels.forEach((label: string, idx: number) => {
      const source = sources[idx];
      const entry: IDataset = {
        label: label,
        // order: idx,
        data: (data ?? []).map((d: Record<string, any>) => d[source]),
      };
      if (axis.type) {
        entry.type = axis.type;
      }
      if (axis.stack) {
        entry.stack = axis.stack;
      }
      if (axis.fill) {
        entry.fill = axis.fill;
      }
      entry.spanGaps = true;
      result.push(entry);
    });

    return result;
  }
}
