"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _dropdownMenu = _interopRequireDefault(require("@atlaskit/dropdown-menu"));
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _useAnalyticsEvents2 = require("../../../../../../../common/analytics/generated/use-analytics-events");
var _extractLozengeActionItems = _interopRequireDefault(require("../../../../../../../extractors/action/extract-lozenge-action-items"));
var _useInvoke = _interopRequireDefault(require("../../../../../../../state/hooks/use-invoke"));
var _utils = require("../../../../../../../state/hooks/use-invoke/utils");
var _useResolve = _interopRequireDefault(require("../../../../../../../state/hooks/use-resolve"));
var _createStatusUpdateRequest = _interopRequireDefault(require("../../../../../../../utils/actions/create-status-update-request"));
var _analytics = require("../../../../../../../utils/analytics/analytics");
var _errorBoundary = _interopRequireDefault(require("./error-boundary"));
var _lozengeActionAnalytics = require("./lozenge-action-analytics");
var _lozengeActionError = _interopRequireDefault(require("./lozenge-action-error"));
var _types = require("./lozenge-action-error/types");
var _lozengeActionItemsGroup = _interopRequireDefault(require("./lozenge-action-items-group"));
var _lozengeActionTrigger = _interopRequireDefault(require("./lozenge-action-trigger"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
var validateItems = function validateItems() {
  var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var text = arguments.length > 1 ? arguments[1] : undefined;
  return items.filter(function (item) {
    return item.text !== text;
  });
};
var LozengeAction = function LozengeAction(_ref) {
  var _action$update;
  var action = _ref.action,
    appearance = _ref.appearance,
    maxWidth = _ref.maxWidth,
    _ref$testId = _ref.testId,
    testId = _ref$testId === void 0 ? 'smart-element-lozenge-action' : _ref$testId,
    text = _ref.text,
    zIndex = _ref.zIndex,
    onAfterChanged = _ref.onAfterChanged,
    trailingMetric = _ref.trailingMetric,
    _ref$shouldRenderToPa = _ref.shouldRenderToParent,
    shouldRenderToParent = _ref$shouldRenderToPa === void 0 ? false : _ref$shouldRenderToPa;
  var _useState = (0, _react.useState)({
      appearance: appearance,
      text: text
    }),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    selected = _useState2[0],
    setSelected = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    isLoaded = _useState4[0],
    setIsLoaded = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
    isLoading = _useState6[0],
    setIsLoading = _useState6[1];
  var _useState7 = (0, _react.useState)(false),
    _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
    isOpen = _useState8[0],
    setIsOpen = _useState8[1];
  var _useState9 = (0, _react.useState)(),
    _useState0 = (0, _slicedToArray2.default)(_useState9, 2),
    items = _useState0[0],
    setItems = _useState0[1];
  var _useState1 = (0, _react.useState)(),
    _useState10 = (0, _slicedToArray2.default)(_useState1, 2),
    errorMessage = _useState10[0],
    setErrorMessage = _useState10[1];
  var reload = (0, _useResolve.default)();
  var invoke = (0, _useInvoke.default)();
  var _useAnalyticsEvents = (0, _useAnalyticsEvents2.useAnalyticsEvents)(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  (0, _react.useEffect)(function () {
    setSelected({
      text: text,
      appearance: appearance
    });
  }, [text, appearance]);
  var _ref2 = (action === null || action === void 0 || (_action$update = action.update) === null || _action$update === void 0 ? void 0 : _action$update.details) || {},
    url = _ref2.url,
    linkId = _ref2.id,
    invokePreviewAction = _ref2.invokePreviewAction;
  var handleOpenChange = (0, _react.useCallback)( /*#__PURE__*/function () {
    var _ref3 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(args) {
      var responseItems, validItems;
      return _regenerator.default.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            setIsOpen(args.isOpen);
            if (!args.isOpen) {
              _context.next = 24;
              break;
            }
            fireEvent('ui.button.clicked.smartLinkStatusLozenge', {});
            fireEvent('track.smartLinkQuickAction.started', {
              smartLinkActionType: _analytics.TrackQuickActionType.StatusUpdate
            });
            if (!(!isLoaded && action !== null && action !== void 0 && action.read)) {
              _context.next = 24;
              break;
            }
            _context.prev = 5;
            setIsLoading(true);
            _context.next = 9;
            return invoke(action.read, _extractLozengeActionItems.default);
          case 9:
            responseItems = _context.sent;
            validItems = typeof text === 'string' ? validateItems(responseItems, text) : responseItems;
            setItems(validItems);
            setIsLoaded(true);
            if ((validItems === null || validItems === void 0 ? void 0 : validItems.length) === 0) {
              fireEvent('track.smartLinkQuickAction.failed', _lozengeActionAnalytics.permissionLoadErrorAnalyticsPayload);
              setErrorMessage((0, _platformFeatureFlags.fg)('confluence-issue-terminology-refresh') ? _types.LozengeActionErrorMessages.noDataIssueTermRefresh : _types.LozengeActionErrorMessages.noData);
              setIsLoaded(false);
            }
            _context.next = 21;
            break;
          case 16:
            _context.prev = 16;
            _context.t0 = _context["catch"](5);
            setErrorMessage(_types.LozengeActionErrorMessages.unknown);
            setIsLoaded(false);
            fireEvent('track.smartLinkQuickAction.failed', _lozengeActionAnalytics.unknownLoadErrorAnalyticsPayload);
          case 21:
            _context.prev = 21;
            setIsLoading(false);
            return _context.finish(21);
          case 24:
            if (!args.isOpen) {
              setErrorMessage(undefined);
            }
          case 25:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[5, 16, 21, 24]]);
    }));
    return function (_x) {
      return _ref3.apply(this, arguments);
    };
  }(), [action.read, invoke, isLoaded, text, fireEvent]);
  var trigger = (0, _react.useCallback)(function (props) {
    return /*#__PURE__*/_react.default.createElement(_lozengeActionTrigger.default, (0, _extends2.default)({}, props, {
      appearance: selected.appearance,
      isOpen: isOpen,
      maxWidth: maxWidth,
      testId: testId,
      text: selected.text,
      trailingMetric: trailingMetric
    }));
  }, [selected.appearance, selected.text, isOpen, maxWidth, testId, trailingMetric]);
  var handleItemClick = (0, _react.useCallback)( /*#__PURE__*/function () {
    var _ref4 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(id, text, appearance) {
      var updateAction, request;
      return _regenerator.default.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            fireEvent('ui.button.clicked.smartLinkStatusListItem', {});
            updateAction = action === null || action === void 0 ? void 0 : action.update;
            if (!(updateAction && id)) {
              _context2.next = 18;
              break;
            }
            setIsLoading(true);
            request = (0, _createStatusUpdateRequest.default)(updateAction, id);
            _context2.next = 8;
            return invoke(request);
          case 8:
            onAfterChanged === null || onAfterChanged === void 0 || onAfterChanged();
            setSelected({
              appearance: appearance,
              text: text
            });
            setIsLoading(false);
            setIsLoaded(false);
            setIsOpen(false);
            setItems([]);
            fireEvent('track.smartLinkQuickAction.success', {
              smartLinkActionType: _analytics.TrackQuickActionType.StatusUpdate
            });
            if (!url) {
              _context2.next = 18;
              break;
            }
            _context2.next = 18;
            return reload(url, true, undefined, linkId);
          case 18:
            _context2.next = 24;
            break;
          case 20:
            _context2.prev = 20;
            _context2.t0 = _context2["catch"](0);
            setIsLoading(false);
            if ((0, _utils.isInvokeCustomError)(_context2.t0)) {
              setErrorMessage(_context2.t0.message);
              fireEvent('track.smartLinkQuickAction.failed', _lozengeActionAnalytics.validationUpdateErrorAnalyticsPayload);
            } else {
              setErrorMessage(_types.LozengeActionErrorMessages.updateFailed);
              fireEvent('track.smartLinkQuickAction.failed', _lozengeActionAnalytics.unknownUpdateErrorAnalyticsPayload);
            }
          case 24:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[0, 20]]);
    }));
    return function (_x2, _x3, _x4) {
      return _ref4.apply(this, arguments);
    };
  }(), [action === null || action === void 0 ? void 0 : action.update, invoke, linkId, reload, url, fireEvent, onAfterChanged]);
  var dropdownItemGroup = (0, _react.useMemo)(function () {
    if (errorMessage) {
      return /*#__PURE__*/_react.default.createElement(_lozengeActionError.default, {
        errorMessage: errorMessage,
        testId: testId,
        url: url,
        invokePreviewAction: invokePreviewAction
      });
    }
    if (items && items.length > 0) {
      return /*#__PURE__*/_react.default.createElement(_lozengeActionItemsGroup.default, {
        testId: testId,
        items: items,
        onClick: handleItemClick
      });
    }
  }, [errorMessage, handleItemClick, items, invokePreviewAction, testId, url]);
  return /*#__PURE__*/_react.default.createElement(_dropdownMenu.default, {
    isLoading: isLoading,
    isOpen: isOpen,
    onOpenChange: handleOpenChange,
    testId: testId,
    trigger: trigger,
    zIndex: zIndex,
    shouldRenderToParent: shouldRenderToParent
  }, dropdownItemGroup);
};
var _default_1 = (0, _errorBoundary.default)(LozengeAction);
var _default = exports.default = _default_1;