export const defaultLevelsConfig = {
  nonCollapsible: [],
  nonSelectable: []
};
const findItem = (options, targetKey) => options.find(({
  key
}) => key === targetKey) || null;

// get flat options with additional parentKey
export function getFlatOptions(options, parentKey = null, level = 0) {
  if (!options?.length) {
    return [];
  }
  const flatOptions = [];
  options.map(({
    subOptions,
    key,
    ...rest
  }) => {
    const subOptionsFlat = getFlatOptions(subOptions, key, level + 1);
    return [{
      key,
      parentKey,
      level,
      ...rest
    }, ...subOptionsFlat];
  }).forEach(optionsArr => flatOptions.push(...optionsArr));
  return flatOptions;
}

// sort by level, deepest menu first, from top to bottom
export function getKeysSorted(flatOptions) {
  return flatOptions.sort((a, b) => a.level > b.level ? -1 : 1).map(({
    key
  }) => key);
}
export function getAncestorKeys(flatOptions, activeKey) {
  const activeKeys = [];
  const directActive = flatOptions.find(({
    key
  }) => key === activeKey);
  if (directActive?.parentKey) {
    let parent = findItem(flatOptions, directActive.parentKey);
    while (parent) {
      activeKeys.push(parent.key);
      parent = parent.parentKey ? findItem(flatOptions, parent.parentKey) : null;
    }
  }
  return activeKeys;
}