Liferay.Loader.define("document-library-web@5.0.95/document_library/js/categorization/categories/EditCategoriesModal.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/alert', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/loading-indicator', '@frontend-taglib-clay$clayui/modal', 'asset-taglib', 'frontend-js-react-web', 'frontend-js-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', './EditCategoriesContext.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    var _alert = _interopRequireDefault(require("@frontend-taglib-clay$clayui/alert"));

    var _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

    var _form = require("@frontend-taglib-clay$clayui/form");

    var _loadingIndicator = _interopRequireDefault(require("@frontend-taglib-clay$clayui/loading-indicator"));

    var _modal = _interopRequireDefault(require("@frontend-taglib-clay$clayui/modal"));

    var _assetTaglib = require("asset-taglib");

    var _frontendJsReactWeb = require("frontend-js-react-web");

    var _frontendJsWeb = require("frontend-js-web");

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _EditCategoriesContext = _interopRequireDefault(require("./EditCategoriesContext.es"));

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    var URL_SELECTION = '/bulk/v1.0/bulk-selection';
    var URL_UPDATE_CATEGORIES = '/bulk/v1.0/taxonomy-categories/batch';

    var EditCategoriesModal = function EditCategoriesModal(_ref) {
      var fileEntries = _ref.fileEntries,
          folderId = _ref.folderId,
          groupIds = _ref.groupIds,
          _ref$hiddenInput = _ref.hiddenInput,
          hiddenInput = _ref$hiddenInput === void 0 ? 'assetCategoriesIds_' : _ref$hiddenInput,
          observer = _ref.observer,
          onModalClose = _ref.onModalClose,
          pathModule = _ref.pathModule,
          repositoryId = _ref.repositoryId,
          _ref$selectAll = _ref.selectAll,
          selectAll = _ref$selectAll === void 0 ? false : _ref$selectAll,
          selectCategoriesUrl = _ref.selectCategoriesUrl;

      var _useContext = (0, _react.useContext)(_EditCategoriesContext.default),
          namespace = _useContext.namespace;

      var _useState = (0, _react.useState)(true),
          _useState2 = _slicedToArray(_useState, 2),
          append = _useState2[0],
          setAppend = _useState2[1];

      var _useState3 = (0, _react.useState)(''),
          _useState4 = _slicedToArray(_useState3, 2),
          description = _useState4[0],
          setDescription = _useState4[1];

      var _useState5 = (0, _react.useState)([]),
          _useState6 = _slicedToArray(_useState5, 2),
          initialCategories = _useState6[0],
          setInitialCategories = _useState6[1];

      var _useState7 = (0, _react.useState)(true),
          _useState8 = _slicedToArray(_useState7, 2),
          isValid = _useState8[0],
          setIsValid = _useState8[1];

      var _useState9 = (0, _react.useState)(false),
          _useState10 = _slicedToArray(_useState9, 2),
          loading = _useState10[0],
          setLoading = _useState10[1];

      var _useState11 = (0, _react.useState)(false),
          _useState12 = _slicedToArray(_useState11, 2),
          multiple = _useState12[0],
          setMultiple = _useState12[1];

      var _useState13 = (0, _react.useState)([]),
          _useState14 = _slicedToArray(_useState13, 2),
          vocabularies = _useState14[0],
          setVocabularies = _useState14[1];

      var _useState15 = (0, _react.useState)('add'),
          _useState16 = _slicedToArray(_useState15, 2),
          selectedRadioGroupValue = _useState16[0],
          setSelectedRadioGroupValue = _useState16[1];

      var bulkStatusComponent = Liferay.component("".concat(namespace, "BulkStatus"));

      var getDescription = function getDescription(size) {
        if (size === 1) {
          return Liferay.Language.get('you-are-editing-the-categories-for-the-selected-item');
        }

        return Liferay.Util.sub(Liferay.Language.get('you-are-editing-the-common-categories-for-x-items.-select-edit-or-replace-current-categories'), size);
      };

      var getFinalCategories = function getFinalCategories() {
        var categories = new Set();
        vocabularies.forEach(function (_ref2) {
          var selectedItems = _ref2.selectedItems;
          selectedItems.map(function (_ref3) {
            var value = _ref3.value;
            categories.add(parseInt(value, 10));
          });
        });
        return Array.from(categories);
      };

      var fetchCategories = (0, _react.useCallback)(function (url, method, bodyData) {
        var init = {
          body: JSON.stringify(bodyData),
          headers: {
            'Content-Type': 'application/json'
          },
          method: method
        };
        return (0, _frontendJsWeb.fetch)("".concat(pathModule).concat(url), init).then(function (response) {
          return response.json();
        }).catch(function () {
          onModalClose();
        });
      }, [onModalClose, pathModule]);

      var isMounted = (0, _frontendJsReactWeb.useIsMounted)();

      var parseCategories = function parseCategories(categories) {
        return categories.map(function (item) {
          return {
            label: item.taxonomyCategoryName,
            value: item.taxonomyCategoryId
          };
        });
      };

      var parseVocabularies = (0, _react.useCallback)(function (vocabularies) {
        var initialCategories = [];
        var requiredVocabularies = [];
        var vocabulariesList = [];
        vocabularies.forEach(function (vocabulary) {
          var categories = parseCategories(vocabulary.taxonomyCategories || []);
          var categoryIds = categories.map(function (item) {
            return item.value;
          });
          var obj = {
            id: vocabulary.taxonomyVocabularyId.toString(),
            required: vocabulary.required,
            selectedCategoryIds: categoryIds.join(','),
            selectedItems: categories,
            singleSelect: !vocabulary.multiValued,
            title: vocabulary.name
          };
          vocabulariesList.push(obj);

          if (vocabulary.required) {
            requiredVocabularies.push(obj);
          }

          initialCategories = initialCategories.concat(categoryIds);
        });
        setInitialCategories(initialCategories);
        return vocabulariesList;
      }, []);
      (0, _react.useEffect)(function () {
        var selection = {
          documentIds: fileEntries,
          selectionScope: {
            folderId: folderId,
            repositoryId: repositoryId,
            selectAll: selectAll
          }
        };
        var urlCategories = "/bulk/v1.0/sites/".concat(groupIds[0], "/taxonomy-vocabularies/common");
        Promise.all([fetchCategories(urlCategories, 'POST', selection), fetchCategories(URL_SELECTION, 'POST', selection)]).then(function (_ref4) {
          var _ref5 = _slicedToArray(_ref4, 2),
              responseCategories = _ref5[0],
              responseSelection = _ref5[1];

          if (responseCategories && responseSelection) {
            if (isMounted()) {
              setLoading(false);
              setDescription(getDescription(responseSelection.size));
              setMultiple(fileEntries.length > 1 || selectAll);
              setVocabularies(parseVocabularies(responseCategories.items || []));
            }
          }
        });
      }, [fetchCategories, fileEntries, fileEntries.length, folderId, groupIds, isMounted, parseVocabularies, repositoryId, selectAll]);
      return (/*#__PURE__*/_react.default.createElement(_modal.default, {
          observer: observer,
          size: "md"
        }, /*#__PURE__*/_react.default.createElement(_modal.default.Header, null, Liferay.Language.get('edit-categories')), /*#__PURE__*/_react.default.createElement("form", {
          onSubmit: function handleSubmit(event) {
            event.preventDefault();
            var finalCategories = getFinalCategories();
            var addedCategories = [];

            if (!append) {
              addedCategories = finalCategories;
            } else {
              addedCategories = finalCategories.filter(function (categoryId) {
                return initialCategories.indexOf(categoryId) == -1;
              });
            }

            var removedCategories = initialCategories.filter(function (category) {
              return finalCategories.indexOf(category) == -1;
            });
            fetchCategories(URL_UPDATE_CATEGORIES, append ? 'PATCH' : 'PUT', {
              documentBulkSelection: {
                documentIds: fileEntries,
                selectionScope: {
                  folderId: folderId,
                  repositoryId: repositoryId,
                  selectAll: selectAll
                }
              },
              taxonomyCategoryIdsToAdd: addedCategories,
              taxonomyCategoryIdsToRemove: removedCategories
            }).then(function () {
              onModalClose();

              if (bulkStatusComponent) {
                bulkStatusComponent.startWatch();
              }
            });
          }
        }, /*#__PURE__*/_react.default.createElement(_modal.default.Body, null, loading && /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, null), selectAll && /*#__PURE__*/_react.default.createElement(_alert.default, {
          title: ""
        }, Liferay.Language.get('this-operation-will-not-be-applied-to-any-of-the-selected-folders')), /*#__PURE__*/_react.default.createElement("p", null, description), multiple && /*#__PURE__*/_react.default.createElement(_form.ClayRadioGroup, {
          name: "add-replace",
          onSelectedValueChange: function handleMultiSelectOptionChange(value) {
            setAppend(value === 'add');
            setSelectedRadioGroupValue(value);
          },
          selectedValue: selectedRadioGroupValue
        }, /*#__PURE__*/_react.default.createElement(_form.ClayRadio, {
          checked: "true",
          label: Liferay.Language.get('edit'),
          value: "add"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "form-text"
        }, Liferay.Language.get('these-categories-replace-all-existing-categories'))), /*#__PURE__*/_react.default.createElement(_form.ClayRadio, {
          label: Liferay.Language.get('replace'),
          value: "replace"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "form-text"
        }, Liferay.Language.get('these-categories-replace-all-existing-categories')))), vocabularies && /*#__PURE__*/_react.default.createElement(_assetTaglib.AssetCategoriesSelector, {
          eventName: "".concat(namespace, "selectCategories"),
          groupIds: groupIds,
          id: "".concat(namespace, "assetTagsSelector"),
          inputName: "".concat(namespace).concat(hiddenInput),
          onVocabulariesChange: function handleVocabulariesChange(newVocabularies) {
            var requiredVocabularies = newVocabularies.filter(function (vocabulary) {
              return vocabulary.required && !vocabulary.selectedItems.length;
            });
            var isInvalid = requiredVocabularies.length ? requiredVocabularies.some(function (item) {
              return item.required && !item.selectedItems.length;
            }) : false;
            setIsValid(!isInvalid);
            setVocabularies(newVocabularies);
          },
          portletURL: selectCategoriesUrl,
          useFallbackInput: true,
          vocabularies: vocabularies
        })), /*#__PURE__*/_react.default.createElement(_modal.default.Footer, {
          last: /*#__PURE__*/_react.default.createElement(_button.default.Group, {
            spaced: true
          }, /*#__PURE__*/_react.default.createElement(_button.default, {
            displayType: "secondary",
            onClick: onModalClose
          }, Liferay.Language.get('cancel')), /*#__PURE__*/_react.default.createElement(_button.default, {
            disabled: !isValid,
            displayType: "primary",
            type: "submit"
          }, Liferay.Language.get('save')))
        })))
      );
    };

    var _default = EditCategoriesModal;
    exports.default = _default;
    //# sourceMappingURL=EditCategoriesModal.es.js.map
  }
});
//# sourceMappingURL=EditCategoriesModal.es.js.map