function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import isEmpty from 'lodash/isEmpty';
import * as React from 'react';
import { useIntl } from 'react-intl';
import { useNotification } from '@box/blueprint-web';
import { UnifiedShareModal } from '@box/unified-share-modal';
import { withBlueprintModernization } from '../common/withBlueprintModernization';
import { fetchAvatars, fetchCollaborators, fetchCurrentUser, fetchItem } from './apis';
import { CONTENT_SHARING_ERRORS } from './constants';
import { useContactService, useSharingService } from './hooks';
import { convertCollabsResponse, convertItemResponse } from './utils';
import messages from './messages';
function ContentSharingV2({
  api,
  children,
  config: usmConfig,
  itemId,
  itemType,
  onClose,
  onError,
  onSendSharedLink,
  variant
}) {
  const {
    formatMessage
  } = useIntl();
  const {
    addNotification
  } = useNotification();
  const [avatarUrlMap, setAvatarUrlMap] = React.useState(null);
  const [item, setItem] = React.useState(null);
  const [hasError, setHasError] = React.useState(false);
  const [sharedLink, setSharedLink] = React.useState(null);
  const [sharingServiceProps, setSharingServiceProps] = React.useState(null);
  const [currentUser, setCurrentUser] = React.useState(null);
  const [collaborationRoles, setCollaborationRoles] = React.useState(null);
  const [collaborators, setCollaborators] = React.useState(null);
  const [collaboratorsData, setCollaboratorsData] = React.useState(null);
  const [owner, setOwner] = React.useState({
    email: '',
    id: '',
    name: ''
  });
  const [isEnterpriseUser, setIsEnterpriseUser] = React.useState(null);
  const config = React.useMemo(() => {
    return _objectSpread({
      collaborationMessage: false,
      sharedLinkEmail: !!onSendSharedLink
    }, usmConfig);
  }, [onSendSharedLink, usmConfig]);
  const sharingService = useSharingService({
    api,
    avatarUrlMap,
    collaborators,
    currentUser,
    item,
    itemId,
    itemType,
    onSendSharedLink,
    sharedLink,
    sharingServiceProps,
    setCollaborators,
    setItem,
    setSharedLink
  });
  const {
    contactService
  } = useContactService(api, itemId, currentUser?.id);

  // Handle successful GET requests to /files or /folders
  const handleGetItemSuccess = React.useCallback(itemData => {
    const {
      collaborationRoles: collaborationRolesFromApi,
      item: itemFromApi,
      ownedBy,
      sharedLink: sharedLinkFromApi,
      sharingService: sharingServicePropsFromApi
    } = convertItemResponse(itemData);
    setItem(itemFromApi);
    setSharedLink(sharedLinkFromApi);
    setSharingServiceProps(sharingServicePropsFromApi);
    setCollaborationRoles(collaborationRolesFromApi);
    setOwner({
      email: ownedBy.login,
      id: ownedBy.id,
      name: ownedBy.name
    });
  }, []);

  // Handle initial data retrieval errors
  const getError = React.useCallback(error => {
    // display only one component-level notification at a time
    if (hasError) {
      return;
    }
    let errorMessage;
    if (error.status) {
      errorMessage = messages[CONTENT_SHARING_ERRORS[error.status]];
    } else if (error.response && error.response.status) {
      errorMessage = messages[CONTENT_SHARING_ERRORS[error.response.status]];
    } else {
      errorMessage = messages.loadingError;
    }
    if (!errorMessage) {
      errorMessage = messages.defaultErrorNoticeText;
    }
    setHasError(true);
    addNotification({
      closeButtonAriaLabel: formatMessage(messages.noticeCloseLabel),
      sensitivity: 'foreground',
      styledText: formatMessage(errorMessage),
      typeIconAriaLabel: formatMessage(messages.errorNoticeIcon),
      variant: 'error'
    });
  }, [addNotification, formatMessage, hasError]);

  // Reset state if the API has changed
  React.useEffect(() => {
    setHasError(false);
    setItem(null);
    setSharedLink(null);
    setCurrentUser(null);
    setIsEnterpriseUser(null);
    setCollaborationRoles(null);
    setAvatarUrlMap(null);
    setCollaborators(null);
    setCollaboratorsData(null);
  }, [api]);

  // Get initial data for the item
  React.useEffect(() => {
    if (!api || isEmpty(api) || item) return;
    (async () => {
      try {
        const itemData = await fetchItem({
          api,
          itemId,
          itemType
        });
        handleGetItemSuccess(itemData);
      } catch (error) {
        getError(error);
        onError?.(error);
      }
    })();
  }, [api, item, itemId, itemType, sharedLink, getError, handleGetItemSuccess, onError]);

  // Get current user
  React.useEffect(() => {
    if (!api || isEmpty(api) || !item || currentUser) return;
    const getUserSuccess = userData => {
      if (!userData) {
        return;
      }
      const {
        enterprise,
        hostname,
        id,
        login
      } = userData;
      const emailDomain = login && /@/.test(login) ? login.split('@')[1] : undefined;
      setCurrentUser({
        id,
        email: login,
        emailDomain
      });
      setSharingServiceProps(prevSharingServiceProps => _objectSpread(_objectSpread({}, prevSharingServiceProps), {}, {
        serverUrl: hostname ? `${hostname}v/` : ''
      }));
      setIsEnterpriseUser(!!enterprise);
    };
    (async () => {
      try {
        const userData = await fetchCurrentUser({
          api,
          itemId
        });
        getUserSuccess(userData);
      } catch (error) {
        getError(error);
      }
    })();
  }, [api, currentUser, item, itemId, itemType, sharedLink, getError]);

  // Set canChangeExpiration to false for non-enterprise (individual) users on every sharedLink update
  React.useEffect(() => {
    if (isEnterpriseUser !== false || !sharedLink?.settings?.canChangeExpiration) {
      return;
    }
    setSharedLink(prevSharedLink => {
      if (!prevSharedLink) {
        return prevSharedLink;
      }
      return _objectSpread(_objectSpread({}, prevSharedLink), {}, {
        settings: _objectSpread(_objectSpread({}, prevSharedLink.settings), {}, {
          canChangeExpiration: false
        })
      });
    });
  }, [isEnterpriseUser, sharedLink]);

  // Get collaborators
  React.useEffect(() => {
    if (!api || isEmpty(api) || !item || collaboratorsData) return;
    (async () => {
      try {
        const response = await fetchCollaborators({
          api,
          itemId,
          itemType
        });
        setCollaboratorsData(response);
      } catch {
        setCollaboratorsData({
          entries: [],
          next_marker: null
        });
      }
    })();
  }, [api, collaboratorsData, item, itemId, itemType]);

  // Get avatars when collaborators are available
  React.useEffect(() => {
    if (avatarUrlMap || !collaboratorsData || !collaboratorsData.entries || !owner.id) return;
    (async () => {
      const ownerEntry = {
        accessible_by: {
          id: owner.id,
          login: owner.email,
          name: owner.name
        }
      };
      const response = await fetchAvatars({
        api,
        itemId,
        collaborators: [...collaboratorsData.entries, ownerEntry]
      });
      setAvatarUrlMap(response);
    })();
  }, [api, avatarUrlMap, collaboratorsData, itemId, owner]);
  React.useEffect(() => {
    if (avatarUrlMap && collaboratorsData && currentUser && owner) {
      const collaboratorsWithAvatars = convertCollabsResponse(collaboratorsData, currentUser, owner, avatarUrlMap);
      setCollaborators(collaboratorsWithAvatars);
    }
  }, [avatarUrlMap, collaboratorsData, currentUser, owner]);
  const handleOpenChange = open => {
    if (!open) {
      onClose?.();
    }
  };
  return item && /*#__PURE__*/React.createElement(UnifiedShareModal, {
    config: config,
    collaborationRoles: collaborationRoles,
    collaborators: collaborators,
    contactService: contactService,
    currentUser: currentUser,
    item: item,
    onOpenChange: handleOpenChange,
    sharedLink: sharedLink,
    sharingService: sharingService,
    variant: variant
  }, children);
}
export default withBlueprintModernization(ContentSharingV2);
//# sourceMappingURL=ContentSharingV2.js.map