import { __assign, __awaiter, __generator } from "tslib";
import * as sessionReplay from '@amplitude/session-replay-browser';
import { VERSION } from './version';
var SessionReplayPlugin = /** @class */ (function () {
    function SessionReplayPlugin(options) {
        this.name = SessionReplayPlugin.pluginName;
        this.type = 'enrichment';
        this.sr = {
            flush: sessionReplay.flush,
            getSessionId: sessionReplay.getSessionId,
            getSessionReplayProperties: sessionReplay.getSessionReplayProperties,
            init: sessionReplay.init,
            setSessionId: sessionReplay.setSessionId,
            shutdown: sessionReplay.shutdown,
        };
        this.options = __assign({ forceSessionTracking: false }, options);
        this.srInitOptions = this.options;
    }
    SessionReplayPlugin.prototype.setup = function (config, _client) {
        var _a, _b, _c, _d, _e;
        return __awaiter(this, void 0, void 0, function () {
            var error_1;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        _f.trys.push([0, 2, , 3]);
                        /* istanbul ignore next */
                        config === null || config === void 0 ? void 0 : config.loggerProvider.log("Installing @amplitude/plugin-session-replay, version ".concat(VERSION, "."));
                        this.config = config;
                        if (this.options.forceSessionTracking) {
                            if (typeof config.defaultTracking === 'boolean') {
                                if (config.defaultTracking === false) {
                                    config.defaultTracking = {
                                        pageViews: false,
                                        formInteractions: false,
                                        fileDownloads: false,
                                        sessions: true,
                                    };
                                }
                            }
                            else {
                                config.defaultTracking = __assign(__assign({}, config.defaultTracking), { sessions: true });
                            }
                        }
                        this.srInitOptions = {
                            instanceName: this.config.instanceName,
                            deviceId: (_a = this.options.deviceId) !== null && _a !== void 0 ? _a : this.config.deviceId,
                            optOut: this.config.optOut,
                            sessionId: this.options.customSessionId ? undefined : this.config.sessionId,
                            loggerProvider: this.config.loggerProvider,
                            logLevel: this.config.logLevel,
                            flushMaxRetries: this.config.flushMaxRetries,
                            serverZone: this.config.serverZone,
                            configServerUrl: this.options.configServerUrl,
                            trackServerUrl: this.options.trackServerUrl,
                            sampleRate: this.options.sampleRate,
                            privacyConfig: {
                                blockSelector: (_b = this.options.privacyConfig) === null || _b === void 0 ? void 0 : _b.blockSelector,
                                maskSelector: (_c = this.options.privacyConfig) === null || _c === void 0 ? void 0 : _c.maskSelector,
                                unmaskSelector: (_d = this.options.privacyConfig) === null || _d === void 0 ? void 0 : _d.unmaskSelector,
                                defaultMaskLevel: (_e = this.options.privacyConfig) === null || _e === void 0 ? void 0 : _e.defaultMaskLevel,
                            },
                            debugMode: this.options.debugMode,
                            shouldInlineStylesheet: this.options.shouldInlineStylesheet,
                            version: { type: 'plugin', version: VERSION },
                            performanceConfig: this.options.performanceConfig,
                            storeType: this.options.storeType,
                            experimental: this.options.experimental,
                        };
                        return [4 /*yield*/, this.sr.init(config.apiKey, this.srInitOptions).promise];
                    case 1:
                        _f.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        error_1 = _f.sent();
                        /* istanbul ignore next */
                        config === null || config === void 0 ? void 0 : config.loggerProvider.error("Session Replay: Failed to initialize due to ".concat(error_1.message));
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.onSessionIdChanged = function (sessionId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.config.loggerProvider.debug("Analytics session id is changed to ".concat(sessionId, ", SR session id is ").concat(String(this.sr.getSessionId()), "."));
                        return [4 /*yield*/, this.sr.setSessionId(sessionId).promise];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.onOptOutChanged = function (optOut) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.config.loggerProvider.debug("optOut is changed to ".concat(String(optOut), ", calling ").concat(optOut ? 'sessionReplay.shutdown()' : 'sessionReplay.init()', "."));
                        if (!optOut) return [3 /*break*/, 1];
                        this.sr.shutdown();
                        return [3 /*break*/, 3];
                    case 1: return [4 /*yield*/, this.sr.init(this.config.apiKey, this.srInitOptions).promise];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.execute = function (event) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var sessionId, sessionRecordingProperties, sessionId, sessionRecordingProperties, error_2;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 8, , 9]);
                        if (!this.options.customSessionId) return [3 /*break*/, 4];
                        sessionId = this.options.customSessionId(event);
                        if (!sessionId) return [3 /*break*/, 3];
                        if (!(sessionId !== this.sr.getSessionId())) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.sr.setSessionId(sessionId).promise];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2:
                        sessionRecordingProperties = this.sr.getSessionReplayProperties();
                        event.event_properties = __assign(__assign({}, event.event_properties), sessionRecordingProperties);
                        _b.label = 3;
                    case 3: return [3 /*break*/, 7];
                    case 4:
                        sessionId = this.config.sessionId;
                        if (!(sessionId && sessionId !== this.sr.getSessionId())) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.sr.setSessionId(sessionId).promise];
                    case 5:
                        _b.sent();
                        _b.label = 6;
                    case 6:
                        // Treating config.sessionId as source of truth, if the event's session id doesn't match, the
                        // event is not of the current session (offline/late events). In that case, don't tag the events
                        if (sessionId && sessionId === event.session_id) {
                            sessionRecordingProperties = this.sr.getSessionReplayProperties();
                            event.event_properties = __assign(__assign({}, event.event_properties), sessionRecordingProperties);
                        }
                        _b.label = 7;
                    case 7: return [2 /*return*/, Promise.resolve(event)];
                    case 8:
                        error_2 = _b.sent();
                        /* istanbul ignore next */
                        (_a = this.config) === null || _a === void 0 ? void 0 : _a.loggerProvider.error("Session Replay: Failed to enrich event due to ".concat(error_2.message));
                        return [2 /*return*/, Promise.resolve(event)];
                    case 9: return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.teardown = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                try {
                    this.sr.shutdown();
                    // the following are initialized in setup() which will always be called first
                    // here we reset them to null to prevent memory leaks
                    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                    // @ts-ignore
                    this.config = null;
                }
                catch (error) {
                    /* istanbul ignore next */
                    (_a = this.config) === null || _a === void 0 ? void 0 : _a.loggerProvider.error("Session Replay: teardown failed due to ".concat(error.message));
                }
                return [2 /*return*/];
            });
        });
    };
    SessionReplayPlugin.prototype.getSessionReplayProperties = function () {
        return this.sr.getSessionReplayProperties();
    };
    SessionReplayPlugin.pluginName = '@amplitude/plugin-session-replay-browser';
    return SessionReplayPlugin;
}());
export { SessionReplayPlugin };
export var sessionReplayPlugin = function (options) {
    return new SessionReplayPlugin(options);
};
//# sourceMappingURL=session-replay.js.map