import { combineProviders } from '../provider-helpers';
/**
 * Allow to run methods from the `ExtensionProvider` interface across all providers seamlessly.
 * This handles promise racing and discards rejected promises safely.
 */
export default (extensionProviders => {
  let providersCache = [];
  const {
    invokeSingle,
    invokeList
  } = combineProviders(extensionProviders);
  return {
    getExtensions() {
      return invokeList('getExtensions');
    },
    async preload() {
      if (providersCache.length === 0) {
        providersCache = await Promise.all(extensionProviders.map(provider => Promise.resolve(provider)));
      }
      await Promise.all(providersCache.map(provider => {
        var _provider$preload;
        return provider === null || provider === void 0 ? void 0 : (_provider$preload = provider.preload) === null || _provider$preload === void 0 ? void 0 : _provider$preload.call(provider);
      }));
    },
    getPreloadedExtension(type, key) {
      if (providersCache.length === 0) {
        // preload() has not been called yet
        return;
      }
      for (const provider of providersCache) {
        try {
          var _provider$getPreloade;
          const result = provider === null || provider === void 0 ? void 0 : (_provider$getPreloade = provider.getPreloadedExtension) === null || _provider$getPreloade === void 0 ? void 0 : _provider$getPreloade.call(provider, type, key);
          if (result) {
            return result;
          }
        } catch {
          // Not every provider will implement this method.
          // In that case we would get error from other providers in the loop
          // and undefined from that particular provider.
          // We can safely ignore it and fallback to the async getExtension when nothing was found.
        }
      }
    },
    getExtension(type, key) {
      return invokeSingle('getExtension', [type, key]);
    },
    search(keyword) {
      return invokeList('search', [keyword]);
    },
    getAutoConverter() {
      return invokeList('getAutoConverter');
    }
  };
});