import { TaskState } from './TaskState';
import { computed, makeObservable, observable, runInAction } from 'mobx';
import { queryMarketListing } from '@wix/bex-utils/@wix/ambassador-devcenter-app-market-listing-v1-market-listing/http';
export class AppsState {
    constructor(params) {
        this.initTask = new TaskState();
        this.apps = [];
        this.container = params.container;
        this.dataExtension = params.dataExtension;
        makeObservable(this, {
            apps: observable.ref,
            appNames: 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);
        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) {
        if (app.appId && 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(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;
    }
}
//# sourceMappingURL=AppsState.js.map