import type { GridRowDef, FieldKeys } from '../types';

/**
 * Converts grid rows to tree data format using groupField as base column for `path` generation.
 * @link https://mui.com/components/data-grid/group-pivot/#tree-data
 */
export const convertChildsToTreeData = (rows: GridRowDef[], groupField: FieldKeys) => {
  const newRows: GridRowDef[] = [];
  rows?.forEach(row => {
    convertRecursively(row, []);
  });
  return newRows;

  function convertRecursively(row: GridRowDef, pathItems: string[] = []) {
    const { childs, ...newRow } = row;
    const pathItem = newRow[groupField] as string;
    pathItems = [...pathItems, pathItem];
    newRow.path = pathItems;
    newRows.push(newRow);
    if (childs) {
      childs.forEach(child => {
        convertRecursively(child, pathItems);
      });
    }
  }
};
