"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.AndroidDeviceDebugService = void 0;
const helpers_1 = require("../common/helpers");
const debug_service_base_1 = require("./debug-service-base");
const constants_1 = require("../common/constants");
const decorators_1 = require("../common/decorators");
const yok_1 = require("../common/yok");
const _ = require("lodash");
class AndroidDeviceDebugService extends debug_service_base_1.DebugServiceBase {
    get platform() {
        return "android";
    }
    constructor(device, $devicesService, $cleanupService, $errors, $logger, $androidProcessService, $staticConfig, $net, $deviceLogProvider) {
        super(device, $devicesService);
        this.device = device;
        this.$devicesService = $devicesService;
        this.$cleanupService = $cleanupService;
        this.$errors = $errors;
        this.$logger = $logger;
        this.$androidProcessService = $androidProcessService;
        this.$staticConfig = $staticConfig;
        this.$net = $net;
        this.$deviceLogProvider = $deviceLogProvider;
        this.deviceIdentifier = device.deviceInfo.identifier;
    }
    async debug(debugData, debugOptions) {
        this._packageName = debugData.applicationIdentifier;
        const result = await this.debugCore(debugData.applicationIdentifier, debugOptions);
        if (debugOptions.start && !debugOptions.justlaunch) {
            const pid = await this.$androidProcessService.getAppProcessId(this.deviceIdentifier, debugData.applicationIdentifier);
            if (pid) {
                this.$deviceLogProvider.setApplicationPidForDevice(this.deviceIdentifier, pid);
                this.$deviceLogProvider.setProjectDirForDevice(this.device.deviceInfo.identifier, debugData.projectDir);
                const device = await this.$devicesService.getDevice(this.deviceIdentifier);
                await device.openDeviceLogStream();
            }
        }
        return result;
    }
    debugStop() {
        return this.removePortForwarding();
    }
    async removePortForwarding(packageName) {
        const port = await this.getForwardedDebugPort(this.device.deviceInfo.identifier, packageName || this._packageName);
        return this.device.adb.executeCommand([
            "forward",
            "--remove",
            `tcp:${port}`,
        ]);
    }
    async getForwardedDebugPort(deviceId, packageName) {
        let port = -1;
        const forwardsResult = await this.device.adb.executeCommand([
            "forward",
            "--list",
        ]);
        const unixSocketName = `${packageName}-inspectorServer`;
        const regexp = new RegExp(`(?:${deviceId} tcp:)([\\d]+)(?= localabstract:${unixSocketName})`, "g");
        const match = regexp.exec(forwardsResult);
        if (match) {
            port = parseInt(match[1]);
        }
        else {
            port = await this.$net.getAvailablePortInRange(40000);
            await this.unixSocketForward(port, `${unixSocketName}`);
        }
        await this.$cleanupService.addCleanupCommand({
            command: await this.$staticConfig.getAdbFilePath(),
            args: ["-s", deviceId, "forward", "--remove", `tcp:${port}`],
        });
        return port;
    }
    async unixSocketForward(local, remote) {
        await this.device.adb.executeCommand([
            "forward",
            `tcp:${local}`,
            `localabstract:${remote}`,
        ]);
    }
    async debugCore(appId, debugOptions) {
        const result = { debugUrl: null };
        if (debugOptions.stop) {
            await this.removePortForwarding();
            return result;
        }
        await this.validateRunningApp(this.deviceIdentifier, appId);
        if (debugOptions.debugBrk) {
            await this.waitForDebugServer(appId);
        }
        const debugPort = await this.getForwardedDebugPort(this.deviceIdentifier, appId);
        await this.printDebugPort(this.deviceIdentifier, debugPort);
        result.debugUrl = this.getChromeDebugUrl(debugOptions, debugPort);
        return result;
    }
    async printDebugPort(deviceId, port) {
        this.$logger.info("device: " + deviceId + " debug port: " + port + "\n");
    }
    async validateRunningApp(deviceId, packageName) {
        if (!(await this.isAppRunning(packageName, deviceId))) {
            this.$errors.fail(`The application ${packageName} does not appear to be running on ${deviceId} or is not built with debugging enabled. Try starting the application manually.`);
        }
    }
    async waitForDebugServer(appId) {
        const debuggerStartedFilePath = `${constants_1.LiveSyncPaths.ANDROID_TMP_DIR_NAME}/${appId}-debugger-started`;
        const waitText = `0 ${debuggerStartedFilePath}`;
        let maxWait = 12;
        let debuggerStarted = false;
        while (maxWait > 0 && !debuggerStarted) {
            const forwardsResult = await this.device.adb.executeShellCommand([
                "ls",
                "-s",
                debuggerStartedFilePath,
            ]);
            maxWait--;
            debuggerStarted = forwardsResult.indexOf(waitText) === -1;
            if (!debuggerStarted) {
                await (0, helpers_1.sleep)(500);
            }
        }
        if (debuggerStarted) {
            this.$logger.info("# NativeScript Debugger started #");
        }
        else {
            this.$logger.warn("# NativeScript Debugger did not start in time #");
        }
    }
    async isAppRunning(appIdentifier, deviceIdentifier) {
        const debuggableApps = await this.$androidProcessService.getDebuggableApps(deviceIdentifier);
        return !!_.find(debuggableApps, (a) => a.appIdentifier === appIdentifier);
    }
}
exports.AndroidDeviceDebugService = AndroidDeviceDebugService;
__decorate([
    (0, decorators_1.performanceLog)()
], AndroidDeviceDebugService.prototype, "debug", null);
__decorate([
    (0, decorators_1.performanceLog)()
], AndroidDeviceDebugService.prototype, "debugCore", null);
yok_1.injector.register("androidDeviceDebugService", AndroidDeviceDebugService, false);
