"use strict";
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextDebugger = exports.Debugger = void 0;
const events_1 = require("events");
const utils_1 = require("../../utils/utils");
const consoleApiSource = __importStar(require("../../generated/consoleApiSource"));
class Debugger {
    async onContextCreated(context) {
        ContextDebugger.getOrCreate(context);
        if (utils_1.debugMode() === 'console')
            await context.extendInjectedScript(consoleApiSource.source);
    }
    async onBeforeCall(sdkObject, metadata) {
        var _a;
        await ((_a = ContextDebugger.lookup(sdkObject.attribution.context)) === null || _a === void 0 ? void 0 : _a.onBeforeCall(sdkObject, metadata));
    }
    async onBeforeInputAction(sdkObject, metadata) {
        var _a;
        await ((_a = ContextDebugger.lookup(sdkObject.attribution.context)) === null || _a === void 0 ? void 0 : _a.onBeforeInputAction(sdkObject, metadata));
    }
}
exports.Debugger = Debugger;
const symbol = Symbol('ContextDebugger');
class ContextDebugger extends events_1.EventEmitter {
    constructor() {
        super();
        this._pauseOnNextStatement = false;
        this._pausedCallsMetadata = new Map();
        this._enabled = utils_1.debugMode() === 'inspector';
        if (this._enabled)
            this.pauseOnNextStatement();
    }
    static getOrCreate(context) {
        let contextDebugger = context[symbol];
        if (!contextDebugger) {
            contextDebugger = new ContextDebugger();
            context[symbol] = contextDebugger;
        }
        return contextDebugger;
    }
    static lookup(context) {
        if (!context)
            return;
        return context[symbol];
    }
    async onBeforeCall(sdkObject, metadata) {
        if (shouldPauseOnCall(sdkObject, metadata) || (this._pauseOnNextStatement && shouldPauseOnStep(sdkObject, metadata)))
            await this.pause(sdkObject, metadata);
    }
    async onBeforeInputAction(sdkObject, metadata) {
        if (this._enabled && this._pauseOnNextStatement)
            await this.pause(sdkObject, metadata);
    }
    async pause(sdkObject, metadata) {
        this._enabled = true;
        metadata.pauseStartTime = utils_1.monotonicTime();
        const result = new Promise(resolve => {
            this._pausedCallsMetadata.set(metadata, { resolve, sdkObject });
        });
        this.emit(ContextDebugger.Events.PausedStateChanged);
        return result;
    }
    resume(step) {
        this._pauseOnNextStatement = step;
        const endTime = utils_1.monotonicTime();
        for (const [metadata, { resolve }] of this._pausedCallsMetadata) {
            metadata.pauseEndTime = endTime;
            resolve();
        }
        this._pausedCallsMetadata.clear();
        this.emit(ContextDebugger.Events.PausedStateChanged);
    }
    pauseOnNextStatement() {
        this._pauseOnNextStatement = true;
    }
    isPaused(metadata) {
        if (metadata)
            return this._pausedCallsMetadata.has(metadata);
        return !!this._pausedCallsMetadata.size;
    }
    pausedDetails() {
        const result = [];
        for (const [metadata, { sdkObject }] of this._pausedCallsMetadata)
            result.push({ metadata, sdkObject });
        return result;
    }
}
exports.ContextDebugger = ContextDebugger;
ContextDebugger.Events = {
    PausedStateChanged: 'pausedstatechanged'
};
function shouldPauseOnCall(sdkObject, metadata) {
    var _a;
    if (!((_a = sdkObject.attribution.browser) === null || _a === void 0 ? void 0 : _a.options.headful) && !utils_1.isUnderTest())
        return false;
    return metadata.method === 'pause';
}
function shouldPauseOnStep(sdkObject, metadata) {
    return metadata.method === 'goto' || metadata.method === 'close';
}
//# sourceMappingURL=debugger.js.map