Liferay.Loader.define("app-builder-web@1.0.58/js/components/permissions/PermissionsModal.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/management-toolbar', '@frontend-taglib-clay$clayui/modal', 'data-engine-taglib', 'frontend-js-react-web$react', '../../components/loading/Loading.es', '../../components/table/Table.es', '../../utils/client.es', '../../utils/toast.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 _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

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

    var _managementToolbar = _interopRequireDefault(require("@frontend-taglib-clay$clayui/management-toolbar"));

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

    var _dataEngineTaglib = require("data-engine-taglib");

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

    var _Loading = require("../../components/loading/Loading.es");

    var _Table = _interopRequireDefault(require("../../components/table/Table.es"));

    var _client = require("../../utils/client.es");

    var _toast = require("../../utils/toast.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 _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;
    }

    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;
      }
    }

    var _default = function _default(_ref) {
      var actions = _ref.actions,
          endpoint = _ref.endpoint,
          _ref$isDisabled = _ref.isDisabled,
          isDisabled = _ref$isDisabled === void 0 ? function () {
        return false;
      } : _ref$isDisabled,
          isOpen = _ref.isOpen,
          _ref$onClose = _ref.onClose,
          onClose = _ref$onClose === void 0 ? function () {} : _ref$onClose,
          _ref$onSave = _ref.onSave,
          onSave = _ref$onSave === void 0 ? function () {
        return Promise.resolve();
      } : _ref$onSave,
          _ref$rolesFilter = _ref.rolesFilter,
          rolesFilter = _ref$rolesFilter === void 0 ? function () {
        return true;
      } : _ref$rolesFilter,
          title = _ref.title;

      var _useModal = (0, _modal.useModal)({
        onClose: onClose
      }),
          observer = _useModal.observer,
          close = _useModal.onClose;

      var columns = [{
        key: 'name',
        sortable: false,
        value: Liferay.Language.get('role')
      }].concat(_toConsumableArray(actions));

      var _useState = (0, _react.useState)({
        isLoading: true,
        permissions: [],
        roles: [],
        searchText: ''
      }),
          _useState2 = _slicedToArray(_useState, 2),
          state = _useState2[0],
          setState = _useState2[1];

      (0, _react.useEffect)(function () {
        if (!isOpen || !endpoint) {
          return;
        }

        setState({
          isLoading: true,
          permissions: [],
          roles: [],
          searchText: ''
        });
        (0, _client.getItem)('/o/headless-admin-user/v1.0/roles').then(function (_ref2) {
          var _ref2$items = _ref2.items,
              roles = _ref2$items === void 0 ? [] : _ref2$items;
          roles = roles.filter(rolesFilter);
          setState(function (prevState) {
            return _objectSpread({}, prevState, {
              roles: roles
            });
          });
          var roleNames = roles.map(function (_ref3) {
            var name = _ref3.name;
            return name;
          }).join(',');
          return (0, _client.getItem)(endpoint, {
            roleNames: roleNames
          });
        }).then(function (_ref4) {
          var _ref4$items = _ref4.items,
              permissions = _ref4$items === void 0 ? [] : _ref4$items;
          setState(function (prevState) {
            return _objectSpread({}, prevState, {
              isLoading: false,
              permissions: permissions
            });
          });
        })["catch"](function () {
          return setState(function (prevState) {
            return _objectSpread({}, prevState, {
              isLoading: false
            });
          });
        });
      }, [endpoint, isOpen, rolesFilter]);
      var isLoading = state.isLoading,
          permissions = state.permissions,
          roles = state.roles,
          searchText = state.searchText;

      if (!isOpen) {
        return _react["default"].createElement(_react["default"].Fragment, null);
      }

      var isChecked = function isChecked(roleName, actionId) {
        return permissions.some(function (_ref5) {
          var actionIds = _ref5.actionIds,
              name = _ref5.roleName;
          return name === roleName && actionIds.includes(actionId);
        });
      };

      var handleOnSave = function handleOnSave() {
        return Promise.all([(0, _client.updateItem)({
          endpoint: endpoint,
          item: permissions
        }), onSave(permissions)]).then(function () {
          return close();
        }).then(function () {
          return (0, _toast.successToast)();
        })["catch"](function () {
          return (0, _toast.errorToast)();
        });
      };

      var togglePermission = function togglePermission(roleName, actionId) {
        var exists = permissions.some(function (_ref6) {
          var name = _ref6.roleName;
          return roleName === name;
        });
        var newPermissions = exists ? permissions : permissions.concat({
          actionIds: [],
          roleName: roleName
        });
        newPermissions = newPermissions.map(function (permission) {
          if (permission.roleName !== roleName) {
            return permission;
          }

          var actionIds = permission.actionIds;
          return _objectSpread({}, permission, {
            actionIds: actionIds.includes(actionId) ? actionIds.filter(function (id) {
              return id !== actionId;
            }) : actionIds.concat(actionId)
          });
        });
        setState(function (prevState) {
          return _objectSpread({}, prevState, {
            permissions: newPermissions
          });
        });
      };

      var filteredRoles = roles.filter(function (_ref7) {
        var name = _ref7.name;
        return new RegExp(searchText, 'ig').test(name);
      }).map(function (_ref8) {
        var id = _ref8.id,
            name = _ref8.name;
        var item = {
          id: id,
          name: _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement(_icon["default"], {
            symbol: "user"
          }), " ", name)
        };
        actions.forEach(function (_ref9) {
          var key = _ref9.key;
          item = _objectSpread({}, item, _defineProperty({}, key, _react["default"].createElement("input", {
            checked: isChecked(name, key),
            disabled: isDisabled(name, key),
            name: key,
            onChange: function onChange() {
              return togglePermission(name, key);
            },
            type: "checkbox"
          })));
        });
        return item;
      });
      return _react["default"].createElement(_modal["default"], {
        observer: observer,
        size: "full-screen"
      }, _react["default"].createElement(_modal["default"].Header, null, title || Liferay.Language.get('permissions')), _react["default"].createElement(_modal["default"].Body, null, _react["default"].createElement(_managementToolbar["default"], null, _react["default"].createElement(_dataEngineTaglib.SearchInput, {
        onChange: function onChange(searchText) {
          return setState(function (prevState) {
            return _objectSpread({}, prevState, {
              searchText: searchText
            });
          });
        },
        searchText: searchText
      })), _react["default"].createElement(_Loading.Loading, {
        isLoading: isLoading
      }, _react["default"].createElement(_Table["default"], {
        align: "center",
        columns: columns,
        items: filteredRoles
      }))), _react["default"].createElement(_modal["default"].Footer, {
        last: _react["default"].createElement(_button["default"].Group, {
          spaced: true
        }, _react["default"].createElement(_button["default"], {
          displayType: "secondary",
          onClick: function onClick() {
            return close();
          }
        }, Liferay.Language.get('cancel')), _react["default"].createElement(_button["default"], {
          onClick: function onClick() {
            return handleOnSave();
          }
        }, Liferay.Language.get('save')))
      }));
    };

    exports["default"] = _default;
    //# sourceMappingURL=PermissionsModal.es.js.map
  }
});
//# sourceMappingURL=PermissionsModal.es.js.map