import React, { useState } from 'react';
import noop from 'lodash/noop';
import API from '../../../api';
/**
 * Generate the sendInvites() function, which is used for inviting collaborators in the USM.
 *
 * @param {API} api
 * @param {string} itemID
 * @param {ItemType} itemType
 * @param {UseInvitesOptions} options
 */
function useInvites(api, itemID, itemType, options) {
  const [sendInvites, setSendInvites] = useState(null);
  const {
    collaborators,
    handleSuccess = noop,
    handleError = noop,
    isContentSharingV2Enabled,
    setIsLoading = noop,
    transformRequest,
    transformResponse = arg => arg
  } = options;
  React.useEffect(() => {
    if (sendInvites || isContentSharingV2Enabled && !collaborators) return;
    const itemData = {
      id: itemID,
      type: itemType
    };
    const sendCollabRequest = collab => {
      return new Promise((resolve, reject) => {
        api.getCollaborationsAPI(false).addCollaboration(itemData, collab, response => {
          handleSuccess(response);
          resolve(transformResponse(response));
        }, error => {
          handleError(error);
          reject(error);
        });
      });
    };
    const createPostCollaborationFn = () => async collabRequest => {
      if (!transformRequest) return Promise.resolve(null);
      const {
        users,
        groups
      } = transformRequest(collabRequest);
      setIsLoading(true);
      try {
        return await Promise.all([...users.map(user => sendCollabRequest(user)), ...groups.map(group => sendCollabRequest(group))]);
      } finally {
        setIsLoading(false);
      }
    };
    if (!sendInvites) {
      setSendInvites(createPostCollaborationFn);
    }
  }, [api, collaborators, handleError, handleSuccess, isContentSharingV2Enabled, itemID, itemType, sendInvites, setIsLoading, transformRequest, transformResponse]);
  return sendInvites;
}
export default useInvites;
//# sourceMappingURL=useInvites.js.map