"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtensionProfilerService = exports.ProfileSessionState = void 0;
const tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/ban-ts-comment */
const fs_extra_1 = require("fs-extra");
const di_1 = require("@opensumi/di");
const node_logger_1 = require("@opensumi/ide-core-node/lib/logger/node-logger");
const common_1 = require("../common");
var ProfileSessionState;
(function (ProfileSessionState) {
    ProfileSessionState[ProfileSessionState["None"] = 0] = "None";
    ProfileSessionState[ProfileSessionState["Starting"] = 1] = "Starting";
    ProfileSessionState[ProfileSessionState["Running"] = 2] = "Running";
    ProfileSessionState[ProfileSessionState["Stopping"] = 3] = "Stopping";
})(ProfileSessionState || (exports.ProfileSessionState = ProfileSessionState = {}));
let ExtensionProfilerService = class ExtensionProfilerService {
    constructor() {
        this.sessionMap = new Map();
    }
    async $startProfile(clientId) {
        this.logger.verbose(`Try enable inspect port for ${clientId}`);
        const enabled = await this.extensionService.tryEnableInspectPort(clientId);
        if (enabled) {
            const inspectPort = await this.extensionService.getProcessInspectPort(clientId);
            if (inspectPort && typeof inspectPort === 'number') {
                const session = await this.doStartProfiler(inspectPort);
                this.sessionMap.set(clientId, session);
            }
        }
    }
    async doStartProfiler(port) {
        // @ts-ignore
        const profiler = await import('v8-inspect-profiler');
        const session = await profiler.startProfiling({ port, checkForPaused: true });
        return {
            stop: async () => {
                const profile = await session.stop();
                return profile;
            },
        };
    }
    async $stopProfile(clientId) {
        if (!this.sessionMap.has(clientId)) {
            this.logger.verbose(`No ${clientId} profiling session found.`);
            return false;
        }
        this.logger.verbose(`find ${clientId} session, stop...`);
        const session = this.sessionMap.get(clientId);
        try {
            const profileResult = await (session === null || session === void 0 ? void 0 : session.stop());
            if (profileResult) {
                this.lastProfile = profileResult.profile;
                return true;
            }
            return false;
        }
        catch (err) {
            this.logger.error(`Stop profiling session fail, reason: \n ${err.message || err}`);
            return false;
        }
    }
    async $saveLastProfile(savePath) {
        await (0, fs_extra_1.writeFile)(savePath, JSON.stringify(this.lastProfile ? this.lastProfile : {}, null, '\t'));
        this.lastProfile = null;
    }
};
exports.ExtensionProfilerService = ExtensionProfilerService;
tslib_1.__decorate([
    (0, di_1.Autowired)(common_1.IExtensionNodeService),
    tslib_1.__metadata("design:type", Object)
], ExtensionProfilerService.prototype, "extensionService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(node_logger_1.INodeLogger),
    tslib_1.__metadata("design:type", Object)
], ExtensionProfilerService.prototype, "logger", void 0);
exports.ExtensionProfilerService = ExtensionProfilerService = tslib_1.__decorate([
    (0, di_1.Injectable)()
], ExtensionProfilerService);
//# sourceMappingURL=extension.profiler.service.js.map