Liferay.Loader.define("app-builder-workflow-web@1.0.42/js/pages/apps/edit/EditApp.es", ['module', 'exports', 'require', 'app-builder-web/js/AppContext.es', 'app-builder-web/js/components/control-menu/ControlMenu.es', 'app-builder-web/js/components/loading/Loading.es', 'app-builder-web/js/pages/apps/SelectObjectsDropDown.es', 'app-builder-web/js/pages/apps/edit/EditAppContext.es', 'app-builder-web/js/utils/client.es', 'app-builder-web/js/utils/toast.es', 'frontend-js-web', 'frontend-js-react-web$react', '../../../../css/EditApp.scss', './ApplyAppChangesModal.es', './DeployAppModal.es', './EditAppToolbar.es', './actions.es', './configReducer.es', './sidebar/EditAppSidebar.es', './workflow-builder/WorkflowBuilder.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 _AppContext = require("app-builder-web/js/AppContext.es");

    var _ControlMenu = _interopRequireDefault(require("app-builder-web/js/components/control-menu/ControlMenu.es"));

    var _Loading = require("app-builder-web/js/components/loading/Loading.es");

    var _SelectObjectsDropDown = require("app-builder-web/js/pages/apps/SelectObjectsDropDown.es");

    var _EditAppContext = _interopRequireWildcard(require("app-builder-web/js/pages/apps/edit/EditAppContext.es"));

    var _client = require("app-builder-web/js/utils/client.es");

    var _toast = require("app-builder-web/js/utils/toast.es");

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

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

    require("../../../../css/EditApp.scss");

    var _ApplyAppChangesModal = _interopRequireDefault(require("./ApplyAppChangesModal.es"));

    var _DeployAppModal = _interopRequireDefault(require("./DeployAppModal.es"));

    var _EditAppToolbar = _interopRequireDefault(require("./EditAppToolbar.es"));

    var _actions = require("./actions.es");

    var _configReducer = _interopRequireWildcard(require("./configReducer.es"));

    var _EditAppSidebar = _interopRequireDefault(require("./sidebar/EditAppSidebar.es"));

    var _WorkflowBuilder = _interopRequireDefault(require("./workflow-builder/WorkflowBuilder.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 _objectWithoutProperties(source, excluded) {
      if (source == null) return {};var target = _objectWithoutPropertiesLoose(source, excluded);var key, i;if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];if (excluded.indexOf(key) >= 0) continue;if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;target[key] = source[key];
        }
      }return target;
    }

    function _objectWithoutPropertiesLoose(source, excluded) {
      if (source == null) return {};var target = {};var sourceKeys = Object.keys(source);var key, i;for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];if (excluded.indexOf(key) >= 0) continue;target[key] = source[key];
      }return target;
    }

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

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

    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 _toArray(arr) {
      return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
    }

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

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

    var _default = function _default(_ref) {
      var history = _ref.history,
          appId = _ref.match.params.appId,
          scope = _ref.scope;

      var _useContext = (0, _react.useContext)(_AppContext.AppContext),
          baseResourceURL = _useContext.baseResourceURL,
          getStandaloneURL = _useContext.getStandaloneURL,
          namespace = _useContext.namespace;

      var _useReducer = (0, _react.useReducer)(_configReducer.default, (0, _configReducer.getInitialConfig)()),
          _useReducer2 = _slicedToArray(_useReducer, 2),
          config = _useReducer2[0],
          dispatchConfig = _useReducer2[1];

      var defaultLanguageId = config.dataObject.defaultLanguageId;

      var _useReducer3 = (0, _react.useReducer)(_EditAppContext.reducer, {
        app: {
          active: false,
          appDeployments: [],
          dataLayoutId: null,
          dataListViewId: null,
          name: _defineProperty({}, defaultLanguageId, ''),
          scope: scope
        }
      }),
          _useReducer4 = _slicedToArray(_useReducer3, 2),
          app = _useReducer4[0].app,
          dispatch = _useReducer4[1];

      var _useState = (0, _react.useState)(false),
          _useState2 = _slicedToArray(_useState, 2),
          isAppChangesModalVisible = _useState2[0],
          setAppChangesModalVisible = _useState2[1];

      var _useState3 = (0, _react.useState)(false),
          _useState4 = _slicedToArray(_useState3, 2),
          isDeployModalVisible = _useState4[0],
          setDeployModalVisible = _useState4[1];

      var _useState5 = (0, _react.useState)(false),
          _useState6 = _slicedToArray(_useState5, 2),
          isLoading = _useState6[0],
          setLoading = _useState6[1];

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

      (0, _react.useEffect)(function () {
        if (app.dataDefinitionId && defaultLanguageId) {
          dispatchConfig({
            listItems: {
              fetching: true
            },
            type: _configReducer.UPDATE_LIST_ITEMS
          });
          Promise.all([(0, _actions.getFormViews)(app.dataDefinitionId, defaultLanguageId), (0, _actions.getTableViews)(app.dataDefinitionId, defaultLanguageId)]).then(function (_ref2) {
            var _ref3 = _slicedToArray(_ref2, 2),
                formViews = _ref3[0],
                tableViews = _ref3[1];

            dispatchConfig({
              listItems: {
                fetching: false,
                formViews: formViews,
                tableViews: tableViews
              },
              type: _configReducer.UPDATE_LIST_ITEMS
            });
          }).catch(function () {
            dispatchConfig({
              listItems: {
                fetching: false
              },
              type: _configReducer.UPDATE_LIST_ITEMS
            });
          });
        }
      }, [app.dataDefinitionId, defaultLanguageId]);
      (0, _react.useEffect)(function () {
        var promises = [(0, _actions.getAssigneeRoles)(), (0, _SelectObjectsDropDown.getDataObjects)()];
        dispatchConfig({
          listItems: {
            fetching: true
          },
          type: _configReducer.UPDATE_LIST_ITEMS
        });

        if (appId) {
          setLoading(true);
          Promise.all([(0, _client.getItem)("/o/app-builder/v1.0/apps/".concat(appId)), (0, _client.getItem)("/o/app-builder-workflow/v1.0/apps/".concat(appId, "/app-workflows"))].concat(promises)).then(function (_ref4) {
            var _ref5 = _toArray(_ref4),
                app = _ref5[0],
                previousResults = _ref5.slice(1);

            return (0, _actions.getDataDefinition)(app.dataDefinitionId).then(function (dataDefinition) {
              return [app, dataDefinition].concat(_toConsumableArray(previousResults));
            });
          }).then(function (_ref6) {
            var _ref7 = _toArray(_ref6),
                app = _ref7[0],
                dataDefinition = _ref7[1],
                previousResults = _ref7.slice(2);

            return Promise.all([(0, _actions.getFormViews)(app.dataDefinitionId, dataDefinition.defaultLanguageId), (0, _actions.getTableViews)(app.dataDefinitionId, dataDefinition.defaultLanguageId)]).then(function (results) {
              return [app].concat(_toConsumableArray(previousResults), _toConsumableArray(results));
            });
          }).then(_actions.populateConfigData).then(function (_ref8) {
            var _ref9 = _slicedToArray(_ref8, 2),
                app = _ref9[0],
                config = _ref9[1];

            dispatch({
              app: app,
              type: _EditAppContext.UPDATE_APP
            });
            dispatchConfig({
              config: config,
              type: _configReducer.UPDATE_CONFIG
            });
            setLoading(false);
          }).catch(function () {
            (0, _toast.errorToast)();
            setLoading(false);
            dispatchConfig({
              listItems: {
                fetching: false
              },
              type: _configReducer.UPDATE_LIST_ITEMS
            });
          });
        } else {
          Promise.all(promises).then(function (_ref10) {
            var _ref11 = _slicedToArray(_ref10, 2),
                assigneeRoles = _ref11[0],
                dataObjects = _ref11[1];

            dispatchConfig({
              listItems: {
                assigneeRoles: assigneeRoles,
                dataObjects: dataObjects,
                fetching: false
              },
              type: _configReducer.UPDATE_LIST_ITEMS
            });
          }).catch(function () {
            dispatchConfig({
              listItems: {
                fetching: false
              },
              type: _configReducer.UPDATE_LIST_ITEMS
            });
          });
        }
      }, [appId]);
      var title = Liferay.Language.get('new-workflow-powered-app');

      if (appId) {
        title = Liferay.Language.get('edit-workflow-powered-app');
      }

      var getStandaloneLink = function getStandaloneLink(_ref12) {
        var appDeployments = _ref12.appDeployments,
            id = _ref12.id;
        var isStandalone = appDeployments.some(function (_ref13) {
          var type = _ref13.type;
          return type === 'standalone';
        });
        return isStandalone ? "<a href=\"".concat(getStandaloneURL(id), "\" target=\"_blank\">").concat(Liferay.Language.get('open-standalone-app'), ". ").concat(Liferay.Util.getLexiconIconTpl('shortcut'), "</a>") : '';
      };

      var onCancel = function onCancel() {
        history.push("/".concat(scope));
      };

      var onSave = function onSave() {
        var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
        var deployed = arguments.length > 1 ? arguments[1] : undefined;

        var workflowAppSteps = _toConsumableArray(config.steps);

        var workflowApp = {
          appWorkflowStates: [workflowAppSteps.shift(), workflowAppSteps.pop()],
          appWorkflowTasks: workflowAppSteps.map(function (_ref14) {
            var appWorkflowDataLayoutLinks = _ref14.appWorkflowDataLayoutLinks,
                restProps = _objectWithoutProperties(_ref14, ["appWorkflowDataLayoutLinks"]);

            return _objectSpread(_objectSpread({}, restProps), {}, {
              appWorkflowDataLayoutLinks: appWorkflowDataLayoutLinks.map(function (_ref15) {
                var dataLayoutId = _ref15.dataLayoutId,
                    readOnly = _ref15.readOnly;
                return {
                  dataLayoutId: dataLayoutId,
                  readOnly: readOnly
                };
              }),
              errors: undefined
            });
          })
        };
        var resource = appId ? 'update' : 'add';
        var params = {
          app: JSON.stringify(_objectSpread(_objectSpread({}, app), {}, {
            active: deployed !== null && deployed !== void 0 ? deployed : app.active
          })),
          appWorkflow: JSON.stringify(workflowApp)
        };

        if (appId) {
          params.appBuilderAppId = appId;
        } else {
          params.dataDefinitionId = app.dataDefinitionId;
        }

        (0, _frontendJsWeb.fetch)((0, _frontendJsWeb.createResourceURL)(baseResourceURL, {
          p_p_resource_id: "/app_builder/".concat(resource, "_workflow_app")
        }), {
          body: new URLSearchParams(Liferay.Util.ns(namespace, params)),
          method: 'POST'
        }).then(_client.parseResponse).then(function (app) {
          var message = deployed ? "".concat(Liferay.Language.get('the-app-was-deployed-successfully'), " ").concat(getStandaloneLink(app)) : Liferay.Language.get('the-app-was-saved-successfully');
          callback();
          (0, _toast.successToast)(message);
          setSaving(false);
          onCancel();
        }).catch(function (_ref16) {
          var errorMessage = _ref16.errorMessage;
          callback();
          (0, _toast.errorToast)("".concat(errorMessage));
          setSaving(false);
        });
      };

      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "app-builder-workflow-app"
        }, /*#__PURE__*/_react.default.createElement(_ControlMenu.default, {
          backURL: "../../".concat(scope),
          title: title
        }), /*#__PURE__*/_react.default.createElement(_Loading.Loading, {
          isLoading: isLoading
        }, /*#__PURE__*/_react.default.createElement(_EditAppContext.default.Provider, {
          value: {
            appId: appId,
            config: config,
            dispatch: dispatch,
            dispatchConfig: dispatchConfig,
            isAppChangesModalVisible: isAppChangesModalVisible,
            isDeployModalVisible: isDeployModalVisible,
            setAppChangesModalVisible: setAppChangesModalVisible,
            setDeployModalVisible: setDeployModalVisible,
            state: {
              app: app
            }
          }
        }, /*#__PURE__*/_react.default.createElement(_EditAppToolbar.default, {
          isSaving: isSaving,
          onCancel: onCancel,
          onSave: onSave
        }), /*#__PURE__*/_react.default.createElement(_WorkflowBuilder.default, null), /*#__PURE__*/_react.default.createElement(_EditAppSidebar.default, null), /*#__PURE__*/_react.default.createElement(_ApplyAppChangesModal.default, {
          onSave: onSave
        }), /*#__PURE__*/_react.default.createElement(_DeployAppModal.default, {
          onSave: onSave
        }))))
      );
    };

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