var _a, _b;
import { __assign, __awaiter, __generator, __spreadArrays } from "tslib";
import { getCDN } from './lib/parse-cdn';
if (process.env.ASSET_PATH) {
    if (process.env.ASSET_PATH === '/dist/umd/') {
        // @ts-ignore
        // eslint-disable-next-line @typescript-eslint/camelcase
        __webpack_public_path__ = '/dist/umd/';
    }
    else {
        var cdn = (_b = (_a = window.analytics) === null || _a === void 0 ? void 0 : _a._cdn) !== null && _b !== void 0 ? _b : getCDN();
        if (window.analytics)
            window.analytics._cdn = cdn;
        // @ts-ignore
        // eslint-disable-next-line @typescript-eslint/camelcase
        __webpack_public_path__ = cdn + '/analytics-next/bundles/';
    }
}
import fetch from 'unfetch';
import { Analytics } from './analytics';
import { Context } from './core/context';
import { mergedOptions } from './lib/merged-options';
import { pageEnrichment } from './plugins/page-enrichment';
import { remoteLoader } from './plugins/remote-loader';
import { segmentio } from './plugins/segmentio';
import { validation } from './plugins/validation';
export function loadLegacySettings(writeKey) {
    var _a, _b;
    var cdn = (_b = (_a = window.analytics) === null || _a === void 0 ? void 0 : _a._cdn) !== null && _b !== void 0 ? _b : getCDN();
    return fetch(cdn + "/v1/projects/" + writeKey + "/settings")
        .then(function (res) { return res.json(); })
        .catch(function (err) {
        console.warn('Failed to load settings', err);
        throw err;
    });
}
function hasLegacyDestinations(settings) {
    return (process.env.NODE_ENV !== 'test' &&
        // just one integration means segmentio
        Object.keys(settings.integrations).length > 1);
}
function flushBuffered(analytics) {
    var wa = window.analytics;
    var buffered = 
    // @ts-expect-error
    wa && wa[0] ? __spreadArrays(wa) : [];
    var _loop_1 = function (operation, args) {
        if (
        // @ts-expect-error
        analytics[operation] &&
            // @ts-expect-error
            typeof analytics[operation] === 'function') {
            // flush each individual event as its own task, so not to block initial page loads
            setTimeout(function () {
                var _a;
                // @ts-expect-error
                (_a = analytics[operation]).call.apply(_a, __spreadArrays([analytics], args));
            }, 0);
        }
    };
    for (var _i = 0, buffered_1 = buffered; _i < buffered_1.length; _i++) {
        var _a = buffered_1[_i], operation = _a[0], args = _a.slice(1);
        _loop_1(operation, args);
    }
}
/**
 * With AJS classic, we allow users to call setAnonymousId before the library initialization.
 * This is important because some of the destinations will use the anonymousId during the initialization,
 * and if we set anonId afterwards, that wouldn’t impact the destination.
 */
function flushAnonymousUser(analytics) {
    var wa = window.analytics;
    var buffered = 
    // @ts-expect-error
    wa && wa[0] ? __spreadArrays(wa) : [];
    var anon = buffered.find(function (_a) {
        var op = _a[0];
        return op === 'setAnonymousId';
    });
    if (anon) {
        var id = anon[1];
        analytics.setAnonymousId(id);
    }
}
function registerPlugins(legacySettings, analytics, opts, options, plugins) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, function () {
        var legacyDestinations, _c, mergedSettings, remotePlugins, toRegister, shouldIgnoreSegmentio, ctx;
        var _this = this;
        return __generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    if (!hasLegacyDestinations(legacySettings)) return [3 /*break*/, 2];
                    return [4 /*yield*/, import(
                        /* webpackChunkName: "ajs-destination" */ './plugins/ajs-destination').then(function (mod) {
                            return mod.ajsDestinations(legacySettings, analytics.integrations, opts);
                        })];
                case 1:
                    _c = _d.sent();
                    return [3 /*break*/, 3];
                case 2:
                    _c = [];
                    _d.label = 3;
                case 3:
                    legacyDestinations = _c;
                    if (!legacySettings.legacyVideoPluginsEnabled) return [3 /*break*/, 5];
                    return [4 /*yield*/, import(
                        /* webpackChunkName: "legacyVideos" */ './plugins/legacy-video-plugins').then(function (mod) {
                            return mod.loadLegacyVideoPlugins(analytics);
                        })];
                case 4:
                    _d.sent();
                    _d.label = 5;
                case 5:
                    mergedSettings = mergedOptions(legacySettings, options);
                    return [4 /*yield*/, remoteLoader(legacySettings).catch(function () { return []; })];
                case 6:
                    remotePlugins = _d.sent();
                    toRegister = __spreadArrays([
                        validation,
                        pageEnrichment
                    ], plugins, legacyDestinations, remotePlugins);
                    shouldIgnoreSegmentio = (((_a = opts.integrations) === null || _a === void 0 ? void 0 : _a.All) === false && !opts.integrations['Segment.io']) ||
                        (opts.integrations && opts.integrations['Segment.io'] === false);
                    if (!shouldIgnoreSegmentio) {
                        toRegister.push(segmentio(analytics, mergedSettings['Segment.io'], legacySettings.integrations));
                    }
                    return [4 /*yield*/, analytics.register.apply(analytics, toRegister)];
                case 7:
                    ctx = _d.sent();
                    if (!(Object.keys((_b = legacySettings.enabledMiddleware) !== null && _b !== void 0 ? _b : {}).length > 0)) return [3 /*break*/, 9];
                    return [4 /*yield*/, import(
                        /* webpackChunkName: "remoteMiddleware" */ './plugins/remote-middleware').then(function (_a) {
                            var remoteMiddlewares = _a.remoteMiddlewares;
                            return __awaiter(_this, void 0, void 0, function () {
                                var middleware, promises;
                                return __generator(this, function (_b) {
                                    switch (_b.label) {
                                        case 0: return [4 /*yield*/, remoteMiddlewares(ctx, legacySettings)];
                                        case 1:
                                            middleware = _b.sent();
                                            promises = middleware.map(function (mdw) {
                                                return analytics.addSourceMiddleware(mdw);
                                            });
                                            return [2 /*return*/, Promise.all(promises)];
                                    }
                                });
                            });
                        })];
                case 8:
                    _d.sent();
                    _d.label = 9;
                case 9: return [2 /*return*/, ctx];
            }
        });
    });
}
var AnalyticsBrowser = /** @class */ (function () {
    function AnalyticsBrowser() {
    }
    AnalyticsBrowser.load = function (settings, options) {
        var _a, _b, _c;
        if (options === void 0) { options = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var legacySettings, retryQueue, opts, analytics, plugins, ctx;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0: return [4 /*yield*/, loadLegacySettings(settings.writeKey)];
                    case 1:
                        legacySettings = _d.sent();
                        retryQueue = (_b = (_a = legacySettings.integrations['Segment.io']) === null || _a === void 0 ? void 0 : _a.retryQueue) !== null && _b !== void 0 ? _b : true;
                        opts = __assign({ retryQueue: retryQueue }, options);
                        analytics = new Analytics(settings, opts);
                        plugins = (_c = settings.plugins) !== null && _c !== void 0 ? _c : [];
                        Context.initMetrics(legacySettings.metrics);
                        // needs to be flushed before plugins are registered
                        flushAnonymousUser(analytics);
                        return [4 /*yield*/, registerPlugins(legacySettings, analytics, opts, options, plugins)];
                    case 2:
                        ctx = _d.sent();
                        analytics.initialized = true;
                        analytics.emit('initialize', settings, options);
                        if (options.initialPageview) {
                            analytics.page().catch(console.error);
                        }
                        if (window.location.search.includes('ajs_')) {
                            analytics.queryString(window.location.search).catch(console.error);
                        }
                        flushBuffered(analytics);
                        return [2 /*return*/, [analytics, ctx]];
                }
            });
        });
    };
    AnalyticsBrowser.standalone = function (writeKey, options) {
        return AnalyticsBrowser.load({ writeKey: writeKey }, options).then(function (res) { return res[0]; });
    };
    return AnalyticsBrowser;
}());
export { AnalyticsBrowser };
//# sourceMappingURL=browser.js.map