"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.AppsState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _TaskState = require("./TaskState");
var _mobx = require("mobx");
var _http = require("@wix/bex-utils/@wix/ambassador-devcenter-app-market-listing-v1-market-listing/http");
class AppsState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "initTask", new _TaskState.TaskState());
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "dataExtension", void 0);
    (0, _defineProperty2.default)(this, "apps", []);
    this.container = params.container;
    this.dataExtension = params.dataExtension;
    (0, _mobx.makeObservable)(this, {
      apps: _mobx.observable.ref,
      appNames: _mobx.computed
    });
  }
  init() {
    const {
      initTask,
      dataExtension
    } = this;
    initTask.runOnce(async () => {
      await dataExtension.initTask.status.promise;
      const appIds = (dataExtension.appSchemas || []).map(schema => schema.appDefId).filter(Boolean);
      await this._fetchApps(appIds);
    });
    return () => {};
  }
  async _fetchApps(appIds) {
    if (!appIds.length) {
      return;
    }
    const appRequests = this._getAppsRequests(appIds);

    // Don't care if one of the requests fails, we want to have as many apps as possible
    const responses = await Promise.allSettled(appRequests);
    const allApps = this._aggregateAppsFromResponses(responses);
    (0, _mobx.runInAction)(() => {
      this.apps = allApps;
    });
  }
  get appNames() {
    // Prioritize English, allowing other languages to override it.
    return this.apps.sort(this._sortByEnglishFirst).reduce(this._extractAppNames, {});
  }
  _sortByEnglishFirst(a, b) {
    if (a.languageCode === 'en' && b.languageCode !== 'en') {
      return -1;
    } else if (a.languageCode !== 'en' && b.languageCode === 'en') {
      return 1;
    } else {
      return 0;
    }
  }
  _extractAppNames(acc, app) {
    var _app$basicInfo;
    if (app.appId && (_app$basicInfo = app.basicInfo) != null && _app$basicInfo.name) {
      acc[app.appId] = app.basicInfo.name;
    }
    return acc;
  }
  _getAppsRequests(appIds) {
    // Call the API with batches of 50, since the limit is 100, and we get two languages per app (the requested one + english)
    const batchSize = 50;
    const numBatches = Math.ceil(appIds.length / batchSize);
    const batchRequests = [];
    for (let i = 0; i < numBatches; i++) {
      const batchAppIds = appIds.slice(i * batchSize, (i + 1) * batchSize);
      const request = this.container.errorHandler.withErrorHandler(() => this.container.httpClient.request((0, _http.queryMarketListing)({
        query: {
          filter: {
            appId: batchAppIds,
            languageCode: [this.container.environment.language, 'en'],
            status: 'APPROVED'
          }
        }
      })), {});
      batchRequests.push(request);
    }
    return batchRequests;
  }
  _aggregateAppsFromResponses(responses) {
    const allApps = [];
    responses.forEach(response => {
      if (response.status === 'fulfilled') {
        const {
          data: {
            marketListing: apps
          }
        } = response.value;
        if (apps) {
          allApps.push(...apps);
        }
      }
    });
    return allApps;
  }
}
exports.AppsState = AppsState;
//# sourceMappingURL=AppsState.js.map