"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildMenuItem = buildMenuItem;
exports.createAutoConverterRunner = void 0;
exports.getAutoConvertPatternsFromModule = getAutoConvertPatternsFromModule;
exports.getContextualToolbarItemsFromModule = void 0;
exports.getExtensionAutoConvertersFromProvider = getExtensionAutoConvertersFromProvider;
exports.groupBy = exports.getQuickInsertItemsFromModule = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _manifestHelpers = require("./manifest-helpers");
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var groupBy = exports.groupBy = function groupBy(arr, attr, keyRenamer) {
  return (
    // Ignored via go/ees005
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    arr.reduce(function (acc, item) {
      acc[keyRenamer(item[attr])] = item;
      return acc;
    }, {})
  );
};
function buildMenuItem(manifest, extensionModule) {
  var title = extensionModule.title || manifest.title;
  var key = "".concat(manifest.key, ":").concat(extensionModule.key);
  var node = (0, _manifestHelpers.buildAction)(extensionModule.action, manifest);
  if (!node) {
    throw new Error("Couldn't find any action for ".concat(title, " (").concat(key, ")"));
  }
  return _objectSpread(_objectSpread(_objectSpread({
    key: key,
    title: title,
    extensionType: manifest.type,
    extensionKey: manifest.key,
    keywords: extensionModule.keywords || manifest.keywords || [],
    featured: extensionModule.featured || false,
    categories: extensionModule.categories || manifest.categories || [],
    description: extensionModule.description || manifest.description,
    summary: manifest.summary,
    documentationUrl: manifest.documentationUrl
  }, ((0, _platformFeatureFlags.fg)('cc_fd_wb_create_priority_in_slash_menu_enabled') || (0, _platformFeatureFlags.fg)('rovo_chat_enable_skills_ui_m1')) && {
    priority: extensionModule.priority
  }), extensionModule.lozenge != null && {
    lozenge: extensionModule.lozenge
  }), {}, {
    icon: extensionModule.icon || manifest.icons['48'],
    node: node
  });
}
var getQuickInsertItemsFromModule = exports.getQuickInsertItemsFromModule = function getQuickInsertItemsFromModule(extensions, transformFunction) {
  var _ref;
  var items = extensions.map(function (manifest) {
    var modules = manifest.modules.quickInsert || [];
    return modules.map(function (extensionModule) {
      return buildMenuItem(manifest, extensionModule);
    });
  });
  var flatItems = (_ref = []).concat.apply(_ref, (0, _toConsumableArray2.default)(items));
  return flatItems.map(transformFunction);
};
function getAutoConvertPatternsFromModule(_x) {
  return _getAutoConvertPatternsFromModule.apply(this, arguments);
}
function _getAutoConvertPatternsFromModule() {
  _getAutoConvertPatternsFromModule = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(extensions) {
    var _ref2;
    var items;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return Promise.all(extensions.map(function (manifest) {
            if (manifest.modules.autoConvert && manifest.modules.autoConvert.url) {
              return manifest.modules.autoConvert.url;
            }
            return [];
          }));
        case 2:
          items = _context.sent;
          return _context.abrupt("return", (_ref2 = []).concat.apply(_ref2, (0, _toConsumableArray2.default)(items)));
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _getAutoConvertPatternsFromModule.apply(this, arguments);
}
var createAutoConverterRunner = exports.createAutoConverterRunner = function createAutoConverterRunner(autoConvertHandlers) {
  return function (text) {
    var _iterator = _createForOfIteratorHelper(autoConvertHandlers),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var handler = _step.value;
        var result = handler(text);
        if (result) {
          return result;
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  };
};
function getExtensionAutoConvertersFromProvider(_x2) {
  return _getExtensionAutoConvertersFromProvider.apply(this, arguments);
} // Ignored via go/ees005
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _getExtensionAutoConvertersFromProvider() {
  _getExtensionAutoConvertersFromProvider = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(extensionProviderPromise) {
    var extensionProvider, extensionAutoConverters;
    return _regenerator.default.wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return extensionProviderPromise;
        case 2:
          extensionProvider = _context2.sent;
          _context2.next = 5;
          return extensionProvider.getAutoConverter();
        case 5:
          extensionAutoConverters = _context2.sent;
          return _context2.abrupt("return", createAutoConverterRunner(extensionAutoConverters));
        case 7:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _getExtensionAutoConvertersFromProvider.apply(this, arguments);
}
var logError = function logError(msg) {
  var _console;
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }
  // eslint-disable-next-line no-console
  (_console = console).error.apply(_console, [msg].concat(args));
};
var toolbarItemToButtonConfig = function toolbarItemToButtonConfig(toolbarButton, parentKey) {
  var tooltip = toolbarButton.tooltip,
    tooltipStyle = toolbarButton.tooltipStyle,
    key = toolbarButton.key,
    label = toolbarButton.label,
    ariaLabel = toolbarButton.ariaLabel,
    icon = toolbarButton.icon,
    action = toolbarButton.action,
    disabled = toolbarButton.disabled;
  var itemKey = [parentKey, key].join(':');
  if (typeof action !== 'function') {
    logError("Provided action is not a function for extension toolbar button: ".concat(label, " (").concat(itemKey, ")"));
  }
  var labelAndIcon = {};
  switch (toolbarButton.display) {
    case 'icon':
      if (!icon) {
        logError("icon should be provided for extension toolbar button (".concat(itemKey, "), when display is set to 'icon'"));
      }
      labelAndIcon = {
        icon: icon
      };
      break;
    case 'label':
      if (!label) {
        logError("label should be provided for extension toolbar button (".concat(itemKey, "), when display is set to 'label'"));
      }
      labelAndIcon = {
        label: label
      };
      break;
    default:
      if (!label || !icon) {
        logError("label and icon should be provided for extension toolbar button (".concat(itemKey, "), when display is not set or set to 'icon-and-label'"));
      }
      labelAndIcon = {
        icon: icon,
        label: label
      };
      break;
  }
  return _objectSpread({
    key: itemKey,
    ariaLabel: ariaLabel,
    tooltip: tooltip,
    tooltipStyle: tooltipStyle,
    action: action,
    disabled: disabled
  }, labelAndIcon);
};
var compareContext = function compareContext(contextA, contextB) {
  if (contextA.type === contextB.type && contextA.nodeType === contextB.nodeType) {
    if (contextA.type === 'node') {
      return true;
    }
    if (contextA.type === 'extension' && contextB.type === 'extension') {
      return contextA.extensionKey === contextB.extensionKey && contextA.extensionType === contextB.extensionType;
    }
  }
  return false;
};
var hasDuplicateContext = function hasDuplicateContext(contextualToolbars) {
  if (contextualToolbars.length > 1) {
    var contexts = contextualToolbars.map(function (contextualToolbar) {
      return contextualToolbar.context;
    });
    return contexts.find(function (currentContext, currentIndex) {
      return currentIndex !== contexts.findIndex(function (context) {
        return compareContext(currentContext, context);
      });
    });
  }
};
var getContextualToolbarItemsFromModule = exports.getContextualToolbarItemsFromModule = function getContextualToolbarItemsFromModule(extensions, node, api) {
  return extensions.map(function (extension) {
    if (extension.modules.contextualToolbars) {
      var duplicateContext = hasDuplicateContext(extension.modules.contextualToolbars);
      if (duplicateContext) {
        logError("[contextualToolbars] Duplicate context detected - ".concat(JSON.stringify(duplicateContext), "."));
        return [];
      }
      return extension.modules.contextualToolbars.map(function (contextualToolbar) {
        if (shouldAddExtensionItemForNode(contextualToolbar, node)) {
          var toolbarItems = contextualToolbar.toolbarItems;
          if (typeof toolbarItems === 'function') {
            return toolbarItems(node, api);
          }
          return toolbarItems;
        }
        return [];
      }).flatMap(function (toolbarItems) {
        return toolbarItems.map(function (toolbarItem) {
          if (isToolbarButton(toolbarItem)) {
            return toolbarItemToButtonConfig(toolbarItem, extension.key);
          }
          return toolbarItem;
        });
      });
    }
    return [];
  }).flatMap(function (extensionToolbarButtons) {
    return extensionToolbarButtons;
  });
};
var isToolbarButton = function isToolbarButton(toolbarItem) {
  if ('type' in toolbarItem) {
    return false;
  }
  return true;
};

// defines whether to add toolbar item for the given node
function shouldAddExtensionItemForNode(item, node) {
  var _node$attrs;
  // if item type is a standard node - should match the nodeType
  if (item.context.type === 'node' && item.context.nodeType === node.type) {
    return true;
  }
  // for other cases should be an extension and match the nodeType ("extension" | "inlineExtension" | "bodiedExtension" | "multiBodiedExtension")
  if (item.context.type !== 'extension' || node.type !== item.context.nodeType) {
    return false;
  }

  // in cases where we need custom exclusion depending on the node
  if (item.context.shouldExclude) {
    if (item.context.shouldExclude(node)) {
      return false;
    }
  }
  var _item$context = item.context,
    extensionType = _item$context.extensionType,
    extensionKey = _item$context.extensionKey;

  // if extension type is given - should match extension type
  if (extensionType && extensionType !== ((_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs.extensionType)) {
    return false;
  }
  // if extension key is a string
  if (typeof extensionKey === 'string') {
    var _node$attrs2;
    return extensionKey === ((_node$attrs2 = node.attrs) === null || _node$attrs2 === void 0 ? void 0 : _node$attrs2.extensionKey);
  }
  // if extension key is an array
  if (Array.isArray(extensionKey) && extensionKey.length) {
    var _node$attrs3;
    return extensionKey.includes((_node$attrs3 = node.attrs) === null || _node$attrs3 === void 0 ? void 0 : _node$attrs3.extensionKey);
  }
  return false;
}