Liferay.Loader.define("item-selector-taglib@4.2.11/item_selector_preview/js/ItemSelectorPreview.es", ['module', 'exports', 'require', 'frontend-js-react-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dom', './Carousel.es', './Footer.es', './Header.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 _frontendJsReactWeb = require("frontend-js-react-web");

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

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

    var _reactDom = _interopRequireDefault(require("frontend-js-react-web$react-dom"));

    var _Carousel = _interopRequireDefault(require("./Carousel.es"));

    var _Footer = _interopRequireDefault(require("./Footer.es"));

    var _Header = _interopRequireDefault(require("./Header.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 ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

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

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

    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 KEY_CODE = {
      ESC: 27,
      LEFT: 37,
      RIGTH: 39
    };

    var itemIsImage = function itemIsImage(_ref) {
      var mimeType = _ref.mimeType,
          type = _ref.type;
      return type === 'image' || Boolean(mimeType === null || mimeType === void 0 ? void 0 : mimeType.match(/image.*/));
    };

    var ItemSelectorPreview = function ItemSelectorPreview(_ref2) {
      var container = _ref2.container,
          _ref2$currentIndex = _ref2.currentIndex,
          currentIndex = _ref2$currentIndex === void 0 ? 0 : _ref2$currentIndex,
          editItemURL = _ref2.editItemURL,
          handleSelectedItem = _ref2.handleSelectedItem,
          headerTitle = _ref2.headerTitle,
          items = _ref2.items,
          uploadItemReturnType = _ref2.uploadItemReturnType,
          uploadItemURL = _ref2.uploadItemURL;

      var _useState = (0, _react.useState)(currentIndex),
          _useState2 = _slicedToArray(_useState, 2),
          currentItemIndex = _useState2[0],
          setCurrentItemIndex = _useState2[1];

      var _useState3 = (0, _react.useState)(itemIsImage(items[currentIndex])),
          _useState4 = _slicedToArray(_useState3, 2),
          isImage = _useState4[0],
          setIsImage = _useState4[1];

      var _useState5 = (0, _react.useState)(items),
          _useState6 = _slicedToArray(_useState5, 2),
          itemList = _useState6[0],
          setItemList = _useState6[1];

      var _useState7 = (0, _react.useState)(false),
          _useState8 = _slicedToArray(_useState7, 2),
          reloadOnHide = _useState8[0],
          setReloadOnHide = _useState8[1];

      var infoButtonRef = /*#__PURE__*/_react.default.createRef();

      var isMounted = (0, _frontendJsReactWeb.useIsMounted)();
      var close = (0, _react.useCallback)(function () {
        _reactDom.default.unmountComponentAtNode(container);
      }, [container]);
      var handleClickNext = (0, _react.useCallback)(function () {
        if (itemList.length > 1) {
          setCurrentItemIndex(function (index) {
            var lastIndex = itemList.length - 1;

            return index === lastIndex ? 0 : index + 1;
          });
        }
      }, [itemList.length]);
      var handleClickPrevious = (0, _react.useCallback)(function () {
        if (itemList.length > 1) {
          setCurrentItemIndex(function (index) {
            var lastIndex = itemList.length - 1;

            return index === 0 ? lastIndex : index - 1;
          });
        }
      }, [itemList.length]);
      var handleOnKeyDown = (0, _react.useCallback)(function (e) {
        if (!isMounted()) {
          return;
        }

        switch (e.which || e.keyCode) {
          case KEY_CODE.LEFT:
            handleClickPrevious();
            break;

          case KEY_CODE.RIGTH:
            handleClickNext();
            break;

          case KEY_CODE.ESC:
            e.preventDefault();
            e.stopPropagation();
            close();
            break;

          default:
            break;
        }
      }, [close, handleClickNext, handleClickPrevious, isMounted]);
      var currentItem = itemList[currentItemIndex];

      var updateItemList = function updateItemList(newItemList) {
        setItemList(newItemList);
        setReloadOnHide(true);
      };

      var updateCurrentItem = (0, _react.useCallback)(function (_ref3) {
        var url = _ref3.url,
            value = _ref3.value;

        if (isMounted()) {
          var newItemList = _toConsumableArray(itemList);

          newItemList[currentItemIndex] = _objectSpread(_objectSpread({}, currentItem), {}, {
            url: url,
            value: value
          });
          updateItemList(newItemList);
        }
      }, [currentItem, currentItemIndex, isMounted, itemList]);
      (0, _react.useEffect)(function () {
        document.documentElement.addEventListener('keydown', handleOnKeyDown);
        var updateCurrentItemHandler = Liferay.on('updateCurrentItem', updateCurrentItem);
        Liferay.component('ItemSelectorPreview', ItemSelectorPreview);
        return function () {
          document.documentElement.removeEventListener('keydown', handleOnKeyDown);
          Liferay.detach(updateCurrentItemHandler);
          Liferay.component('ItemSelectorPreview', null);
        };
      }, [handleOnKeyDown, updateCurrentItem]);
      (0, _react.useEffect)(function () {
        var sidenavToggle = infoButtonRef.current;

        if (sidenavToggle) {
          Liferay.SideNavigation.initialize(sidenavToggle, {
            container: '.sidenav-container',
            position: 'right',
            typeMobile: 'fixed',
            width: '320px'
          });
        }

        return function () {
          Liferay.SideNavigation.destroy(sidenavToggle);
        };
      }, [infoButtonRef]);

      var handleSaveEdit = function handleSaveEdit(e) {
        var itemData = e.data.file;
        var editedItemMetadata = {
          groups: [{
            data: [{
              key: Liferay.Language.get('format'),
              value: itemData.type
            }, {
              key: Liferay.Language.get('name'),
              value: itemData.title
            }],
            title: Liferay.Language.get('file-info')
          }]
        };
        var editedItem = {
          fileentryid: currentItem.fileentryid,
          metadata: JSON.stringify(editedItemMetadata),
          returntype: uploadItemReturnType,
          title: itemData.title,
          url: itemData.url,
          value: itemData.resolvedValue
        };
        var updatedItemList = [].concat(_toConsumableArray(itemList), [editedItem]);
        updateItemList(updatedItemList);
        setCurrentItemIndex(updatedItemList.length - 1);
      };

      (0, _react.useEffect)(function () {
        setIsImage(itemIsImage(currentItem));
      }, [currentItem]);
      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "fullscreen item-selector-preview"
        }, /*#__PURE__*/_react.default.createElement(_Header.default, {
          disabledAddButton: !currentItem.url,
          handleClickAdd: function handleClickDone() {
            // LPS-120692
            close();
            handleSelectedItem(currentItem);
          },
          handleClickBack: function handleClickBack() {
            close();

            if (reloadOnHide) {
              var frame = window.frameElement;

              if (frame) {
                frame.contentWindow.location.reload();
              }
            }
          },
          handleClickEdit: function handleClickEdit() {
            var itemTitle = currentItem.title;
            var editDialogTitle = "".concat(Liferay.Language.get('edit'), " ").concat(itemTitle, " (").concat(Liferay.Language.get('copy'), ")");
            var editEntityBaseZIndex = Liferay.zIndex.WINDOW;
            Liferay.Util.editEntity({
              dialog: {
                destroyOnHide: true,
                zIndex: editEntityBaseZIndex + 100
              },
              id: 'Edit_' + itemTitle,
              stack: false,
              title: editDialogTitle,
              uri: editItemURL,
              urlParams: {
                entityURL: currentItem.url,
                saveFileEntryId: currentItem.fileentryid,
                saveFileName: itemTitle,
                saveParamName: 'imageSelectorFileName',
                saveURL: uploadItemURL
              }
            }, handleSaveEdit);
          },
          headerTitle: headerTitle,
          infoButtonRef: infoButtonRef,
          showEditIcon: isImage,
          showInfoIcon: !!currentItem.metadata
        }), /*#__PURE__*/_react.default.createElement(_Carousel.default, {
          currentItem: currentItem,
          handleClickNext: handleClickNext,
          handleClickPrevious: handleClickPrevious,
          isImage: isImage,
          showArrows: itemList.length > 1
        }), /*#__PURE__*/_react.default.createElement(_Footer.default, {
          currentIndex: currentItemIndex,
          title: currentItem.title,
          totalItems: itemList.length
        }))
      );
    };

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