"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFileUploader = exports.findByName = void 0;
var _react = require("react");
var _union = _interopRequireDefault(require("lodash/union"));
var _useFileStructure = require("../hooks/use-file-structure");
var _fileUploaderAdapter = require("./file-uploader-adapter");
var _fileUploaderConstants = require("./file-uploader-constants");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const merge = (a, b, prop) => {
  const filtered = a.filter(aItem => !b.find(bItem => aItem[prop] === bItem[prop]));
  return filtered.concat(b);
};
const findByName = (filesArray, fileName) => {
  return (filesArray || []).find(({
    name
  }) => fileName === name);
};
exports.findByName = findByName;
const useFileUploader = ({
  initialFiles = [],
  isMultiple,
  setErrorMessage
}) => {
  const errors = (0, _fileUploaderConstants.useFileUploaderErrors)();
  const [collectedFileStructure, setCollectedFileStructure] = (0, _react.useState)(initialFiles);
  const [addedFileStructure, setAddedFileStructure] = (0, _react.useState)([]);
  const {
    fileStructure,
    generateFileStructure
  } = (0, _useFileStructure.useFileStructure)({
    fileStructureAdapter: _fileUploaderAdapter.fileUploaderStructureAdapter
  });
  const updateFileStructure = (name, payload) => {
    setCollectedFileStructure(prevState => {
      const file = findByName(prevState, name);
      if (!file) {
        return prevState;
      }
      return (0, _union.default)(prevState, Object.assign(file, payload));
    });
  };
  const removeFileFromStructure = name => {
    setCollectedFileStructure(prevState => {
      return prevState.filter(file => file.name !== name);
    });
  };
  const isFileStructureValid = files => {
    if (!isMultiple && (files.length > 1 || collectedFileStructure.length === 1)) {
      setErrorMessage(errors[_fileUploaderConstants.ERROR_TYPES.SINGLE_ONLY]);
      return false;
    }
    return true;
  };
  (0, _react.useEffect)(() => {
    if (!!fileStructure && !!fileStructure.length && isFileStructureValid(fileStructure)) {
      setCollectedFileStructure(prevState => {
        return merge(prevState, Object.values(fileStructure), 'name');
      });
      setAddedFileStructure(fileStructure);
    }
  }, [fileStructure]);
  return {
    addedFileStructure,
    collectedFileStructure,
    generateFileStructure,
    removeFileFromStructure,
    updateFileStructure
  };
};
exports.useFileUploader = useFileUploader;