import { convertArrayToNestedArray, flatNestedArray } from '../../../utils/array';
/** The `LinePathInputProcessor` class generates chart path options based on input data and previous scale records for a line chart. */
export class LinePathInputProcessor {
  /**
   * This function generates chart path options based on input data and previous scale records.
   *
   * @param {ChartOptions<LineChartDataType>} input - The input parameter is an object of type ChartOptions that contains two properties:
   * dataSource and colors. The dataSource property is of type LineChartDataType and represents the data
   * used to generate the chart. The colors property is an array of strings that represents the colors
   * to be used for the chart.
   * @param {ScaleRecordType} previousOutput - The `previousOutput` parameter is of type
   * `ScaleRecordType` and is the output of the previous step in the chart rendering process. It
   * contains the x and y scales that were calculated in the previous step and are used in this step to
   * generate the positions for the chart path.
   * @returns {ChartPathOptions} A `ChartPathOptions` object is being returned, which contains an array of `positions`
   * generated using the `pathPositionGenerator` and the `xScale` and `yScale` scales from the
   * `previousOutput`, as well as the `colors` from the `dataSource`.
   */
  process(input, previousOutput) {
    const { dataSource, colors } = input;
    const { xScale, yScale } = previousOutput;
    return {
      positions: this.getPathPositions(dataSource, xScale, yScale),
      colors,
    };
  }
  /**
   * convert array to array[], convert x,y position to relative position
   *
   * @param {LineChartDataType['dataSource']} originData origin line data source
   * @param {AxisScale<AxisDomain>} xScale x scale
   * @param {AxisScale<AxisDomain>} yScale y scale
   * @returns {ChartPosition[][]} x,y relative position
   */
  getPathPositions(originData, xScale, yScale) {
    const flatData = flatNestedArray(originData);
    let dataLengthArr = [];
    const flatPathData = flatData.map(({ x, y }) => {
      return {
        x: xScale(x),
        y: yScale(y),
      };
    });
    let pathData = [];
    if (originData && Array.isArray(originData[0])) {
      dataLengthArr = originData.map((item) => item.length);
      pathData = convertArrayToNestedArray(flatPathData, dataLengthArr);
    }
    else {
      pathData = [flatPathData];
    }
    return pathData;
  }
}
