import { filterBy as KendoFilterBy } from "@progress/kendo-react-data-tools";
import {
  mapTree as KendoMapTree,
  extendDataItem as KendoExtendDataItem,
} from "@progress/kendo-react-common";

export const processTreeData = (
  data: any[],
  state: { expanded: any; value: any; filter: any },
  fields: {
    selectField: any;
    expandField: any;
    dataItemKey: any;
    subItemsField: any;
  }
) => {
  const { selectField, expandField, dataItemKey, subItemsField } = fields;
  const { expanded, value, filter } = state;
  const filtering = Boolean(filter && filter.value);

  if (!data || !state || !fields) {
    console.error("Undefined values detected");
    return;
  }

  return KendoMapTree(
    filtering ? KendoFilterBy(data, [filter], subItemsField) : data,
    subItemsField,
    (item) => {
      const props = {
        [expandField]: expanded.includes(item[dataItemKey]),
        [selectField]: value && item[dataItemKey] === value[dataItemKey],
      };
      return filtering
        ? KendoExtendDataItem(item, subItemsField, props)
        : { ...item, ...props };
    }
  );
};

export const expandedState = (
  item: { [x: string]: any },
  dataItemKey: string | number,
  expanded: (string | number)[]
) => {
  const nextExpanded = expanded.slice();
  const itemKey = item[dataItemKey];
  const index = nextExpanded.indexOf(itemKey);
  index === -1 ? nextExpanded.push(itemKey) : nextExpanded.splice(index, 1);

  return nextExpanded;
};
