import React, { useCallback } from "react";
import FsFileUpload from "./FsFileUpload";
import { toFormstackFile } from "../helpers";

export const setMultipleValues = (fieldIdsLiteral, setValue) => async (fileId, value, options) => {
  if (fieldIdsLiteral) {
    const ids = fieldIdsLiteral.split(",");
    const files = await (Array.isArray(value) ? Promise.all(value.map(toFormstackFile)) : []);
    files.forEach((file, idx) => {
      if (idx < ids.length) {
        setValue(ids[idx], file, options);
      }
    });
    // set a value for the given id so it passes validation
    if (files.length > 0) {
      setValue(fileId, "true", options);
    }
  }
};

const FsMultipleFileUpload = ({ fieldIds, id, label, name, errors, register, required, setValue }) => {
  // useCallback was running too often (infinite loop) because calling setValue would inherently
  // update the `fieldIds` array. The contents of the array remain the same, but the array object
  // itself changes.
  const fieldIdsLiteral = Array.isArray(fieldIds) ? fieldIds.join(",") : null;

  const setMultipleValuesCallback = useCallback(
    (fileId, value, options) => setMultipleValues(fieldIdsLiteral, setValue)(fileId, value, options),
    [fieldIdsLiteral, setValue, required]
  );

  return (
    <FsFileUpload
      id={id}
      name={name}
      label={label}
      required={required}
      register={register}
      setValue={setMultipleValuesCallback}
      errors={errors}
      maxFiles={fieldIds.length}
    />
  );
};

export default FsMultipleFileUpload;
