"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fileTreeAdapter = exports.cleanUpPath = exports.FILE_TYPE = void 0;
var _uniqueId = _interopRequireDefault(require("lodash/uniqueId"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const FILE_TYPE = exports.FILE_TYPE = {
  FOLDER: 'folder',
  FILE: 'file'
};
const cleanUpPath = path => path.replace(/^\/|\/$/g, '');

/**
 * Helper functions and data structure to convert file paths into the structure
 * needed to use with the file-tree component.
 */
exports.cleanUpPath = cleanUpPath;
const fileTreeAdapter = fileStructure => {
  const fileTree = fileStructure ?? [];
  const addPath = ({
    path,
    customProps
  }) => {
    let currentLevel = fileTree;
    const finalPath = cleanUpPath(path).split(/\//);
    finalPath.forEach((name, index, originalArray) => {
      const pathToEntity = currentLevel.find(entity => entity.name === name);
      if (pathToEntity) {
        currentLevel = pathToEntity?.content ?? [];
      } else {
        const itemTypeProps = index < originalArray.length - 1 ? {
          id: (0, _uniqueId.default)(),
          type: FILE_TYPE.FOLDER
        } : {
          id: customProps?.id ?? (0, _uniqueId.default)(),
          type: FILE_TYPE.FILE
        };
        const entityStructure = {
          ...itemTypeProps,
          name,
          path: originalArray.slice(0, index + 1).join('/'),
          timestamp: new Date().getTime(),
          content: [],
          ...(customProps ? {
            customProps
          } : {})
        };
        currentLevel.push(entityStructure);
        currentLevel = entityStructure.content;
      }
    });
    return fileTree;
  };
  return {
    fileTree,
    addPath
  };
};
exports.fileTreeAdapter = fileTreeAdapter;