import { useEffect, useRef } from 'react';

const useFileValidation = ({
  fileList,
  setFileList,
  validate,
  createNewFile = false
}) => {
  useEffect(() => {
    if (!validate)
      return;
    const updateFile = (fileId, file) => {
      const index = fileList.findIndex((f) => f.uid === fileId);
      if (index !== -1) {
        const newList = [...fileList];
        const fileToUpdate = createNewFile ? (() => {
          const newFile = new File([file], file.name, { type: file.type });
          Object.assign(newFile, file);
          return newFile;
        })() : file;
        newList.splice(index, 1, fileToUpdate);
        setFileList(newList);
      }
    };
    for (const _file of fileList) {
      if (_file.fileStatus !== "need-validate") {
        continue;
      }
      _file.fileStatus = "validating";
      updateFile(_file.uid, _file);
      validate(_file, fileList).then((result) => {
        if (result.error) {
          _file.error = result.error;
          _file.fileStatus = "error";
        } else {
          _file.error = void 0;
          _file.fileStatus = "success";
          _file.data = result.data;
        }
        updateFile(_file.uid, _file);
        return;
      });
    }
  }, [fileList, setFileList, validate, createNewFile]);
};
const useFileCountErrorClear = ({
  fileList,
  maxCount,
  setError
}) => {
  const fileCountRef = useRef(fileList.length);
  useEffect(() => {
    if (fileList.length === fileCountRef.current) {
      return;
    }
    fileCountRef.current = fileList.length;
    if (fileCountRef.current <= maxCount) {
      setError("");
    }
  }, [fileList.length, maxCount, setError]);
};

export { useFileCountErrorClear, useFileValidation };
