"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserService = exports.CHROME_ADDRESS = exports.CHROME_PORT = void 0;
const inversify_1 = require("inversify");
const index_js_1 = require("../../cdp/index.js");
const config_js_1 = require("../../config.js");
const exception_js_1 = require("../../exception.js");
const logger_js_1 = require("../../logger.js");
const __1 = require("..");
const playwright_js_1 = require("../services/playwright.js");
const session_js_1 = require("../session.js");
const CDP_TIMEOUT = (0, config_js_1.numberConfig)('CDP_TIMEOUT', 120000);
const NAVIGATION_TIMEOUT = (0, config_js_1.numberConfig)('NAVIGATION_TIMEOUT', 30000);
exports.CHROME_PORT = (0, config_js_1.numberConfig)('CHROME_PORT', 9123);
exports.CHROME_ADDRESS = (0, config_js_1.stringConfig)('CHROME_ADDRESS', '127.0.0.1');
const SUSPEND_TARGETS = (0, config_js_1.booleanConfig)('SUSPEND_TARGETS', true);
let BrowserService = class BrowserService extends index_js_1.Browser {
    constructor(logger, _config, playwright) {
        super({ logger });
        this._config = _config;
        this.playwright = playwright;
        this._currentPage = null;
        this.syncConfig();
    }
    async onSessionStart() {
    }
    async onSessionFinish() {
        this.clearInterceptors();
    }
    syncConfig() {
        this.applyConfig({
            chromeAddress: this._config.get(exports.CHROME_ADDRESS),
            chromePort: this._config.get(exports.CHROME_PORT),
            cdpTimeout: this._config.get(CDP_TIMEOUT),
            navigationTimeout: this._config.get(NAVIGATION_TIMEOUT),
            suspendTargets: this._config.get(SUSPEND_TARGETS),
        });
    }
    async connect() {
        await super.connect();
        await this.playwright.connectOverCDP();
    }
    async disconnect() {
        super.disconnect();
        await this.playwright.disconnect();
    }
    getChromePort() {
        return this._config.get(exports.CHROME_PORT);
    }
    async attach(targetId) {
        const playwrightSetCurrentPagePromise = this.playwright.setCurrentPage(targetId);
        this.detach();
        this._currentPage = await this.getPage(targetId);
        if (!this._currentPage) {
            throw new exception_js_1.Exception({
                name: 'AttachFailed',
                message: 'Could not attach to specified target',
                retry: true,
            });
        }
        await playwrightSetCurrentPagePromise;
        this.emit('attached');
    }
    isAttached() {
        return !!this._currentPage;
    }
    isAttachedTo(targetId) {
        if (!this._currentPage) {
            return false;
        }
        return this._currentPage.target.targetId === targetId;
    }
    detach() {
        if (!this.isAttached()) {
            return;
        }
        this.emit('willDetach');
        this._currentPage = null;
        this.emit('detached');
    }
    get page() {
        __1.util.assertPlayback(this._currentPage, `No attached targets`);
        return this._currentPage;
    }
    getCurrentPage() {
        return this._currentPage;
    }
    getCurrentPlaywrightPage() {
        __1.util.assertPlayback(this.playwright.getCurrentPage(), `No attached Playwright page`);
        return this.playwright.getCurrentPage();
    }
    async fetchCurrentPlaywrightPage() {
        let currentPage = this.playwright.getCurrentPage();
        if (!currentPage && this._currentPage?.target?.targetId) {
            await this.playwright.setCurrentPage(this._currentPage?.target.targetId);
            currentPage = this.playwright.getCurrentPage();
        }
        __1.util.assertPlayback(currentPage, `No attached Playwright page`);
        return currentPage;
    }
    async openNewTab() {
        const tab = await this.newTab();
        await this.attach(tab.target.targetId);
    }
    async closeOtherTabs() {
        const currentTarget = this.page.target;
        const pages = [...this.attachedPages()];
        for (const page of pages) {
            if (page.target.targetId !== currentTarget.targetId && page.target.type === 'page') {
                page.close();
            }
        }
    }
};
BrowserService = __decorate([
    (0, inversify_1.injectable)(),
    (0, session_js_1.SessionHandler)(),
    __param(0, (0, inversify_1.inject)(logger_js_1.Logger)),
    __param(1, (0, inversify_1.inject)(config_js_1.Configuration)),
    __param(2, (0, inversify_1.inject)(playwright_js_1.PlaywrightService)),
    __metadata("design:paramtypes", [logger_js_1.Logger,
        config_js_1.Configuration,
        playwright_js_1.PlaywrightService])
], BrowserService);
exports.BrowserService = BrowserService;
//# sourceMappingURL=browser.js.map