Liferay.Loader.define("portal-workflow-metrics-web@2.0.46/js/components/sla/form-page/hooks/useSLAFormState.es", ['module', 'exports', 'require', 'frontend-js-react-web$react', '../../../../shared/hooks/useFetch.es', '../../../../shared/hooks/usePost.es', '../../../../shared/hooks/usePut.es', '../../../../shared/util/duration.es', '../SLAFormConstants.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.useSLAFormState = void 0;

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

    var _useFetch2 = require("../../../../shared/hooks/useFetch.es");

    var _usePost2 = require("../../../../shared/hooks/usePost.es");

    var _usePut = require("../../../../shared/hooks/usePut.es");

    var _duration = require("../../../../shared/util/duration.es");

    var _SLAFormConstants = require("../SLAFormConstants.es");

    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 _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 _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 useSLAFormState = function useSLAFormState(_ref) {
      var errors = _ref.errors,
          id = _ref.id,
          processId = _ref.processId,
          setErrors = _ref.setErrors;

      var _useState = (0, _react.useState)({
        calendarKey: null,
        days: null,
        description: '',
        hours: '',
        name: '',
        pauseNodeKeys: {
          nodeKeys: [],
          status: 0
        },
        processId: processId,
        startNodeKeys: {
          nodeKeys: [],
          status: 0
        },
        status: 0,
        stopNodeKeys: {
          nodeKeys: [],
          status: 0
        }
      }),
          _useState2 = _slicedToArray(_useState, 2),
          sla = _useState2[0],
          setSLA = _useState2[1];

      var body = (0, _react.useMemo)(function () {
        var calendarKey = sla.calendarKey,
            days = sla.days,
            description = sla.description,
            hours = sla.hours,
            name = sla.name,
            pauseNodeKeys = sla.pauseNodeKeys,
            startNodeKeys = sla.startNodeKeys,
            stopNodeKeys = sla.stopNodeKeys;
        var duration = (0, _duration.durationAsMilliseconds)(days, hours);
        return {
          calendarKey: calendarKey,
          description: description,
          duration: duration,
          name: name,
          pauseNodeKeys: {
            nodeKeys: pauseNodeKeys.nodeKeys.map(function (_ref2) {
              var executionType = _ref2.executionType,
                  id = _ref2.id;
              return {
                executionType: executionType,
                id: id
              };
            }),
            status: 0
          },
          processId: processId,
          startNodeKeys: {
            nodeKeys: startNodeKeys.nodeKeys.map(function (_ref3) {
              var executionType = _ref3.executionType,
                  id = _ref3.id;
              return {
                executionType: executionType,
                id: id
              };
            }),
            status: 0
          },
          status: 0,
          stopNodeKeys: {
            nodeKeys: stopNodeKeys.nodeKeys.map(function (_ref4) {
              var executionType = _ref4.executionType,
                  id = _ref4.id;
              return {
                executionType: executionType,
                id: id
              };
            }),
            status: 0
          }
        };
      }, [processId, sla]);

      var _useFetch = (0, _useFetch2.useFetch)({
        callback: function parseSLA(_ref5) {
          var calendarKey = _ref5.calendarKey,
              _ref5$description = _ref5.description,
              description = _ref5$description === void 0 ? '' : _ref5$description,
              duration = _ref5.duration,
              name = _ref5.name,
              status = _ref5.status,
              data = _objectWithoutProperties(_ref5, ["calendarKey", "description", "duration", "name", "status"]);

          var _getDurationValues = (0, _duration.getDurationValues)(duration),
              days = _getDurationValues.days,
              hours = _getDurationValues.hours,
              minutes = _getDurationValues.minutes;

          var formattedHours = (0, _duration.formatHours)(hours, minutes);

          var _map = [data.pauseNodeKeys, data.startNodeKeys, data.stopNodeKeys].map(function (node) {
            if (!node || !node.nodeKeys) {
              return {
                nodeKeys: []
              };
            }

            return node;
          }),
              _map2 = _slicedToArray(_map, 3),
              pauseNodeKeys = _map2[0],
              startNodeKeys = _map2[1],
              stopNodeKeys = _map2[2];

          if (status === 2) {
            if (!startNodeKeys.nodeKeys.length) {
              errors[_SLAFormConstants.START_NODE_KEYS] = Liferay.Language.get('selected-option-is-no-longer-available');
            }

            if (!stopNodeKeys.nodeKeys.length) {
              errors[_SLAFormConstants.STOP_NODE_KEYS] = Liferay.Language.get('selected-option-is-no-longer-available');
            }

            setErrors(errors);
          }

          setSLA({
            calendarKey: calendarKey,
            days: days,
            description: description,
            hours: formattedHours,
            name: name,
            pauseNodeKeys: pauseNodeKeys,
            startNodeKeys: startNodeKeys,
            status: status,
            stopNodeKeys: stopNodeKeys
          });
        },
        url: "/slas/".concat(id)
      }),
          fetchSLA = _useFetch.fetchData;

      var _usePost = (0, _usePost2.usePost)({
        body: body,
        url: "/processes/".concat(processId, "/slas")
      }),
          createSLA = _usePost.postData;

      var updateSLA = (0, _usePut.usePut)({
        body: body,
        url: "/slas/".concat(id)
      });

      var getNodeKeys = function getNodeKeys(nodes) {
        return nodes.map(function (_ref6) {
          var compositeId = _ref6.compositeId;
          return compositeId;
        });
      };

      var saveSLA = (0, _react.useCallback)(function () {
        return id ? updateSLA() : createSLA();
      }, [createSLA, id, updateSLA]);
      return {
        changeNodesKeys: function changeNodesKeys(type, nodeKeys, callback) {
          return function (selectedNodes) {
            var selectedNodeKeys = getNodeKeys(selectedNodes);
            var filteredNodeKeys = nodeKeys.filter(function (_ref7) {
              var compositeId = _ref7.compositeId;
              return selectedNodeKeys.includes("".concat(compositeId));
            });
            var attrString = type === _SLAFormConstants.START_NODE_KEYS ? 'startNodeKeys' : 'stopNodeKeys';
            setSLA(_objectSpread(_objectSpread({}, sla), _defineProperty({}, attrString, {
              nodeKeys: filteredNodeKeys
            })));
            callback(filteredNodeKeys);
          };
        },
        changePauseNodes: function changePauseNodes(pauseNodeKeys, callback) {
          return function (nodes) {
            var nodeKeys = getNodeKeys(nodes);
            var filteredPauseNodeKeys = pauseNodeKeys.filter(function (_ref8) {
              var compositeId = _ref8.compositeId;
              return nodeKeys.includes("".concat(compositeId));
            });
            setSLA(_objectSpread(_objectSpread({}, sla), {
              pauseNodeKeys: {
                nodeKeys: filteredPauseNodeKeys
              }
            }));
            callback(filteredPauseNodeKeys);
          };
        },
        changeValue: function changeValue(name, value) {
          if (name === 'days' && isNaN(value)) {
            value = 0;
          }

          setSLA(function (oldSla) {
            return _objectSpread(_objectSpread({}, oldSla), _defineProperty({}, name, value));
          });
        },
        fetchSLA: fetchSLA,
        getNodeTags: function getNodeTags(nodes) {
          var nodeKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
          return nodes.filter(function (_ref9) {
            var compositeId = _ref9.compositeId;
            return nodeKeys.find(function (node) {
              return "".concat(node.id, ":").concat(node.executionType) === compositeId;
            });
          });
        },
        getPauseNodeTags: function getPauseNodeTags(pauseNodes, pauseNodeKeys) {
          var nodeKeys = pauseNodeKeys || [];
          return pauseNodes.filter(function (_ref10) {
            var id = _ref10.id;
            return nodeKeys.find(function (node) {
              return node.id == id;
            });
          });
        },
        resetNodes: function resetNodes() {
          setSLA({
            pauseNodeKeys: {
              nodeKeys: [],
              status: 0
            },
            startNodeKeys: {
              nodeKeys: [],
              status: 0
            },
            stopNodeKeys: {
              nodeKeys: [],
              status: 0
            }
          });
        },
        saveSLA: saveSLA,
        sla: sla
      };
    };

    exports.useSLAFormState = useSLAFormState;
    //# sourceMappingURL=useSLAFormState.es.js.map
  }
});
//# sourceMappingURL=useSLAFormState.es.js.map