"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IOSDeviceBase = void 0;
const decorators_1 = require("../../decorators");
class IOSDeviceBase {
    constructor() {
        this.cachedSockets = {};
    }
    async getDebugSocket(appId, projectName, projectDir, ensureAppStarted = false) {
        return this.$lockService.executeActionWithLock(async () => {
            if (this.cachedSockets[appId]) {
                return this.cachedSockets[appId];
            }
            await this.attachToDebuggerFoundEvent(appId, projectName, projectDir);
            try {
                if (ensureAppStarted) {
                    await this.applicationManager.startApplication({
                        appId,
                        projectName,
                        projectDir,
                    });
                }
            }
            catch (err) {
                this.$logger.trace(`Unable to start application ${appId} on device ${this.deviceInfo.identifier} in getDebugSocket method. Error is: ${err}`);
            }
            this.cachedSockets[appId] = await this.getDebugSocketCore(appId);
            if (this.cachedSockets[appId]) {
                this.cachedSockets[appId].on("close", async () => {
                    await this.destroyDebugSocket(appId);
                });
            }
            return this.cachedSockets[appId];
        }, `ios-debug-socket-${this.deviceInfo.identifier}-${appId}.lock`);
    }
    async attachToDebuggerFoundEvent(appId, projectName, projectDir) {
        await this.startDeviceLogProcess(projectName, projectDir);
        await this.$iOSDebuggerPortService.attachToDebuggerPortFoundEvent(appId);
    }
    async getDebuggerPort(appId) {
        const port = await this.$iOSDebuggerPortService.getPort({
            deviceId: this.deviceInfo.identifier,
            appId,
        });
        if (!port) {
            this.$errors.fail("Device socket port cannot be found.");
        }
        return port;
    }
    async destroyAllSockets() {
        for (const appId in this.cachedSockets) {
            await this.destroySocketSafe(this.cachedSockets[appId]);
        }
        this.cachedSockets = {};
    }
    async destroyDebugSocket(appId) {
        await this.destroySocketSafe(this.cachedSockets[appId]);
        this.cachedSockets[appId] = null;
    }
    async destroySocketSafe(socket) {
        if (socket && !socket.destroyed) {
            return new Promise((resolve, reject) => {
                socket.on("close", resolve);
                socket.destroy();
            });
        }
    }
    async startDeviceLogProcess(projectName, projectDir) {
        if (projectName) {
            this.$deviceLogProvider.setProjectNameForDevice(this.deviceInfo.identifier, projectName);
            this.$deviceLogProvider.setProjectDirForDevice(this.deviceInfo.identifier, projectDir);
        }
        await this.openDeviceLogStream();
    }
}
exports.IOSDeviceBase = IOSDeviceBase;
__decorate([
    (0, decorators_1.performanceLog)()
], IOSDeviceBase.prototype, "getDebugSocket", null);
