"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IOSDebuggerPortService = void 0;
const constants_1 = require("../common/constants");
const decorators_1 = require("../common/decorators");
const constants_2 = require("../constants");
const yok_1 = require("../common/yok");
class IOSDebuggerPortService {
    constructor($logParserService, $iOSNotification, $devicePlatformsConstants, $logger) {
        this.$logParserService = $logParserService;
        this.$iOSNotification = $iOSNotification;
        this.$devicePlatformsConstants = $devicePlatformsConstants;
        this.$logger = $logger;
        this.mapDebuggerPortData = {};
    }
    getPort(data) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const key = `${data.deviceId}${data.appId}`;
                const retryInterval = 500;
                let retryCount = Math.max((constants_2.APPLICATION_RESPONSE_TIMEOUT_SECONDS * 1000) / retryInterval, 10);
                const interval = setInterval(() => {
                    const port = this.getPortByKey(key);
                    if (port || retryCount === 0) {
                        clearInterval(interval);
                        resolve(port);
                    }
                    else {
                        if (this.mapDebuggerPortData[key] &&
                            this.mapDebuggerPortData[key].error) {
                            clearInterval(interval);
                            reject(this.mapDebuggerPortData[key].error);
                        }
                        else {
                            retryCount--;
                        }
                    }
                }, retryInterval);
            });
        });
    }
    attachToDebuggerPortFoundEvent(appId) {
        return __awaiter(this, void 0, void 0, function* () {
            this.currentAppId = appId;
            this.attachToDebuggerPortFoundEventCore();
            this.attachToAttachRequestEvent();
        });
    }
    attachToDebuggerPortFoundEventCore() {
        this.$logParserService.addParseRule({
            regex: IOSDebuggerPortService.DEBUG_PORT_LOG_REGEX,
            handler: this.handlePortFound.bind(this),
            name: "debugPort",
            platform: this.$devicePlatformsConstants.iOS.toLowerCase(),
        });
        this.$logParserService.addParseRule({
            regex: constants_1.IOS_APP_CRASH_LOG_REG_EXP,
            handler: this.handleAppCrash.bind(this),
            name: "appCrash",
            platform: this.$devicePlatformsConstants.iOS.toLowerCase(),
        });
    }
    handleAppCrash(matches, deviceId) {
        const data = {
            port: 0,
            appId: this.currentAppId,
            deviceId,
            error: new Error("The application has been terminated."),
        };
        this.clearTimeout(data);
        this.setData(data, { port: data.port, error: data.error });
    }
    handlePortFound(matches, deviceId) {
        const data = {
            port: parseInt(matches[1]),
            appId: matches[2],
            deviceId,
        };
        this.$logger.trace(constants_1.DEBUGGER_PORT_FOUND_EVENT_NAME, data);
        this.clearTimeout(data);
        this.setData(data, { port: data.port });
    }
    attachToAttachRequestEvent() {
        this.$iOSNotification.on(constants_1.ATTACH_REQUEST_EVENT_NAME, (data) => {
            this.$logger.trace(constants_1.ATTACH_REQUEST_EVENT_NAME, data);
            const timer = setTimeout(() => {
                this.clearTimeout(data);
                if (!this.getPortByKey(`${data.deviceId}${data.appId}`)) {
                    this.$logger.warn(`NativeScript debugger was not able to get inspector socket port on device ${data.deviceId} for application ${data.appId}.`);
                }
            }, constants_2.APPLICATION_RESPONSE_TIMEOUT_SECONDS * 1000);
            this.setData(data, { port: null, timer });
        });
    }
    getPortByKey(key) {
        if (this.mapDebuggerPortData[key] && this.mapDebuggerPortData[key].port) {
            return this.mapDebuggerPortData[key].port;
        }
        return null;
    }
    setData(data, storedData) {
        const key = `${data.deviceId}${data.appId}`;
        if (!this.mapDebuggerPortData[key]) {
            this.mapDebuggerPortData[key] = {};
        }
        this.mapDebuggerPortData[key].port = storedData.port;
        this.mapDebuggerPortData[key].timer = storedData.timer;
        this.mapDebuggerPortData[key].error = storedData.error;
    }
    clearTimeout(data) {
        const storedData = this.mapDebuggerPortData[`${data.deviceId}${data.appId}`];
        if (storedData && storedData.timer) {
            clearTimeout(storedData.timer);
        }
    }
}
IOSDebuggerPortService.DEBUG_PORT_LOG_REGEX = /NativeScript debugger has opened inspector socket on port (\d+?) for (.*)[.]/;
__decorate([
    (0, decorators_1.cache)()
], IOSDebuggerPortService.prototype, "attachToDebuggerPortFoundEventCore", null);
__decorate([
    (0, decorators_1.cache)()
], IOSDebuggerPortService.prototype, "attachToAttachRequestEvent", null);
exports.IOSDebuggerPortService = IOSDebuggerPortService;
yok_1.injector.register("iOSDebuggerPortService", IOSDebuggerPortService);
