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

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

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

    let x = 0;
    let y = 0;
    (chart?.axis ?? []).forEach((axis: ChartAxis, index: number) => {
      let scale = '';
      let count = 0;
      axis.position = axis.position ?? ChartAxisPosition.Bottom;
      switch (axis.position) {
        case ChartAxisPosition.Left:
        case ChartAxisPosition.Right:
          scale = 'y';
          count = y;
          ++y;
          break;
        case ChartAxisPosition.Bottom:
        case ChartAxisPosition.Top:
          scale = 'x';
          count = x;
          ++x;
          break;
      }
      result[`${scale}${count === 0 ? '' : count}`] = this.getScale(axis);
    });

    return result;
  }

  private getScale(item: ChartAxis): Record<string, any> {
    const opts: Record<string, any> = {};

    if (item.stacked) {
      opts['stacked'] = true;
    }
    if (item.position) {
      opts['position'] = item.position;
    }
    if (item.stack) {
      opts['stack'] = item.stack;
    }
    if (item.min) {
      opts['min'] = item.min;
    }
    if (item.max) {
      opts['max'] = item.max;
    }

    return opts;
  }
}
