"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useDeleteWorkpads = void 0;
var _react = require("react");
var _i18n = require("@kbn/i18n");
var _services = require("../../../services");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const useDeleteWorkpads = () => {
  const workpadService = (0, _services.useWorkpadService)();
  const notifyService = (0, _services.useNotifyService)();
  return (0, _react.useCallback)(async workpadIds => {
    const removedWorkpads = workpadIds.map(async id => {
      try {
        await workpadService.remove(id);
        return {
          id,
          err: null
        };
      } catch (err) {
        return {
          id,
          err
        };
      }
    });
    return Promise.all(removedWorkpads).then(results => {
      const [passes, errored] = results.reduce(([passesArr, errorsArr], result) => {
        if (result.err) {
          errorsArr.push(result.id);
        } else {
          passesArr.push(result.id);
        }
        return [passesArr, errorsArr];
      }, [[], []]);
      const removedIds = workpadIds.filter(id => passes.includes(id));
      if (errored.length > 0) {
        notifyService.error(errors.getDeleteFailureErrorMessage());
      }
      return {
        removedIds,
        errored
      };
    });
  }, [workpadService, notifyService]);
};
exports.useDeleteWorkpads = useDeleteWorkpads;
const errors = {
  getDeleteFailureErrorMessage: () => _i18n.i18n.translate('xpack.canvas.error.useDeleteWorkpads.deleteFailureErrorMessage', {
    defaultMessage: `Couldn't delete all workpads`
  })
};