import _defineProperty from "@babel/runtime/helpers/defineProperty";
import { getAutoConvertPatternsFromModule } from './getAutoConvertPatternsFromModule';
export default class DefaultExtensionProvider {
  constructor(manifests,
  /**
   * Allows for an optional list of pre compiled auto convert handlers to be passed.
   * Useful for performance improvements or to support legacy converters.
   *
   * Warning: If this attribute is passed, this provider will ignore auto convert patterns from the manifests.
   */
  autoConvertHandlers) {
    _defineProperty(this, "manifestsCache", []);
    this.manifestsPromise = Promise.resolve(manifests);
    this.autoConvertHandlers = autoConvertHandlers;
  }
  getExtensions() {
    return this.manifestsPromise;
  }
  async preload() {
    this.manifestsCache = await this.getExtensions();
    const preloadCalls = [];
    for (const manifest of this.manifestsCache) {
      var _manifest$modules;
      const nodes = manifest === null || manifest === void 0 ? void 0 : (_manifest$modules = manifest.modules) === null || _manifest$modules === void 0 ? void 0 : _manifest$modules.nodes;
      if (nodes) {
        Object.values(nodes).forEach(node => {
          var _preloadRender, _ref;
          preloadCalls.push(node === null || node === void 0 ? void 0 : (_preloadRender = (_ref = node).preloadRender) === null || _preloadRender === void 0 ? void 0 : _preloadRender.call(_ref));
        });
      }
    }
    await Promise.allSettled(preloadCalls);
  }
  getPreloadedExtension(type, key) {
    if (!this.manifestsCache) {
      return;
    }
    return this.getExtensionFromManifest(this.manifestsCache, type, key);
  }
  async getExtension(type, key) {
    return this.getExtensionFromManifest(await this.manifestsPromise, type, key);
  }
  getExtensionFromManifest(manifests, type, key) {
    const extension = manifests.find(manifest => manifest.type === type && manifest.key === key);
    if (!extension) {
      throw new Error(`Extension with type "${type}" and key "${key}" not found!`);
    }
    return extension;
  }
  async search(keyword) {
    const extensions = (await this.manifestsPromise).filter(manifest => manifest.title.toLowerCase().includes(keyword.toLowerCase()));
    return extensions;
  }
  async getAutoConverter() {
    if (this.autoConvertHandlers) {
      return this.autoConvertHandlers;
    }
    const autoConverters = getAutoConvertPatternsFromModule(await this.manifestsPromise);
    return autoConverters;
  }
}