import { useEffect, useState } from 'react';
import union from 'lodash/union';
import { useFileStructure } from '../hooks/use-file-structure';
import { fileUploaderStructureAdapter } from './file-uploader-adapter';
import { ERROR_TYPES, useFileUploaderErrors } from './file-uploader-constants';
const merge = (a, b, prop) => {
  const filtered = a.filter(aItem => !b.find(bItem => aItem[prop] === bItem[prop]));
  return filtered.concat(b);
};
export const findByName = (filesArray, fileName) => {
  return (filesArray || []).find(({
    name
  }) => fileName === name);
};
export const useFileUploader = ({
  initialFiles = [],
  isMultiple,
  setErrorMessage
}) => {
  const errors = useFileUploaderErrors();
  const [collectedFileStructure, setCollectedFileStructure] = useState(initialFiles);
  const [addedFileStructure, setAddedFileStructure] = useState([]);
  const {
    fileStructure,
    generateFileStructure
  } = useFileStructure({
    fileStructureAdapter: fileUploaderStructureAdapter
  });
  const updateFileStructure = (name, payload) => {
    setCollectedFileStructure(prevState => {
      const file = findByName(prevState, name);
      if (!file) {
        return prevState;
      }
      return union(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[ERROR_TYPES.SINGLE_ONLY]);
      return false;
    }
    return true;
  };
  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
  };
};