"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _icons = require("@wordpress/icons");
var _data = require("@wordpress/data");
var _coreData = require("@wordpress/core-data");
var _i18n = require("@wordpress/i18n");
var _notices = require("@wordpress/notices");
var _element = require("@wordpress/element");
var _components = require("@wordpress/components");
var _utils = require("./utils");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const trashPost = {
  id: 'move-to-trash',
  label: (0, _i18n.__)('Move to trash'),
  isPrimary: true,
  icon: _icons.trash,
  isEligible(item) {
    if ((0, _utils.isTemplateOrTemplatePart)(item) || item.type === 'wp_block') {
      return false;
    }
    return !!item.status && !['auto-draft', 'trash'].includes(item.status) && item.permissions?.delete;
  },
  supportsBulk: true,
  hideModalHeader: true,
  RenderModal: ({
    items,
    closeModal,
    onActionPerformed
  }) => {
    const [isBusy, setIsBusy] = (0, _element.useState)(false);
    const {
      createSuccessNotice,
      createErrorNotice
    } = (0, _data.useDispatch)(_notices.store);
    const {
      deleteEntityRecord
    } = (0, _data.useDispatch)(_coreData.store);
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalVStack, {
      spacing: "5",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalText, {
        children: items.length === 1 ? (0, _i18n.sprintf)(
        // translators: %s: The item's title.
        (0, _i18n.__)('Are you sure you want to move "%s" to the trash?'), (0, _utils.getItemTitle)(items[0])) : (0, _i18n.sprintf)(
        // translators: %d: The number of items (2 or more).
        (0, _i18n._n)('Are you sure you want to move %d item to the trash ?', 'Are you sure you want to move %d items to the trash ?', items.length), items.length)
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
        justify: "right",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          __next40pxDefaultSize: true,
          variant: "tertiary",
          onClick: closeModal,
          disabled: isBusy,
          accessibleWhenDisabled: true,
          children: (0, _i18n.__)('Cancel')
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          __next40pxDefaultSize: true,
          variant: "primary",
          onClick: async () => {
            setIsBusy(true);
            const promiseResult = await Promise.allSettled(items.map(item => deleteEntityRecord('postType', item.type, item.id.toString(), {}, {
              throwOnError: true
            })));
            // If all the promises were fulfilled with success.
            if (promiseResult.every(({
              status
            }) => status === 'fulfilled')) {
              let successMessage;
              if (promiseResult.length === 1) {
                successMessage = (0, _i18n.sprintf)( /* translators: The item's title. */
                (0, _i18n.__)('"%s" moved to the trash.'), (0, _utils.getItemTitle)(items[0]));
              } else {
                successMessage = (0, _i18n.sprintf)( /* translators: The number of items. */
                (0, _i18n._n)('%s item moved to the trash.', '%s items moved to the trash.', items.length), items.length);
              }
              createSuccessNotice(successMessage, {
                type: 'snackbar',
                id: 'move-to-trash-action'
              });
            } else {
              // If there was at least one failure.
              let errorMessage;
              // If we were trying to delete a single item.
              if (promiseResult.length === 1) {
                const typedError = promiseResult[0];
                if (typedError.reason?.message) {
                  errorMessage = typedError.reason.message;
                } else {
                  errorMessage = (0, _i18n.__)('An error occurred while moving the item to the trash.');
                }
                // If we were trying to delete multiple items.
              } else {
                const errorMessages = new Set();
                const failedPromises = promiseResult.filter(({
                  status
                }) => status === 'rejected');
                for (const failedPromise of failedPromises) {
                  const typedError = failedPromise;
                  if (typedError.reason?.message) {
                    errorMessages.add(typedError.reason.message);
                  }
                }
                if (errorMessages.size === 0) {
                  errorMessage = (0, _i18n.__)('An error occurred while moving the items to the trash.');
                } else if (errorMessages.size === 1) {
                  errorMessage = (0, _i18n.sprintf)( /* translators: %s: an error message */
                  (0, _i18n.__)('An error occurred while moving the item to the trash: %s'), [...errorMessages][0]);
                } else {
                  errorMessage = (0, _i18n.sprintf)( /* translators: %s: a list of comma separated error messages */
                  (0, _i18n.__)('Some errors occurred while moving the items to the trash: %s'), [...errorMessages].join(','));
                }
              }
              createErrorNotice(errorMessage, {
                type: 'snackbar'
              });
            }
            if (onActionPerformed) {
              onActionPerformed(items);
            }
            setIsBusy(false);
            closeModal?.();
          },
          isBusy: isBusy,
          disabled: isBusy,
          accessibleWhenDisabled: true,
          children: (0, _i18n._x)('Trash', 'verb')
        })]
      })]
    });
  }
};
var _default = exports.default = trashPost;
//# sourceMappingURL=trash-post.js.map