"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) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
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");
class AndroidDeviceDebugService extends debug_service_base_1.DebugServiceBase {
    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;
    }
    get platform() {
        return "android";
    }
    debug(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            this._packageName = debugData.applicationIdentifier;
            const result = yield this.debugCore(debugData.applicationIdentifier, debugOptions);
            if (debugOptions.start && !debugOptions.justlaunch) {
                const pid = yield 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 = yield this.$devicesService.getDevice(this.deviceIdentifier);
                    yield device.openDeviceLogStream();
                }
            }
            return result;
        });
    }
    debugStop() {
        return this.removePortForwarding();
    }
    removePortForwarding(packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            const port = yield this.getForwardedDebugPort(this.device.deviceInfo.identifier, packageName || this._packageName);
            return this.device.adb.executeCommand(["forward", "--remove", `tcp:${port}`]);
        });
    }
    getForwardedDebugPort(deviceId, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            let port = -1;
            const forwardsResult = yield 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 = yield this.$net.getAvailablePortInRange(40000);
                yield this.unixSocketForward(port, `${unixSocketName}`);
            }
            yield this.$cleanupService.addCleanupCommand({ command: yield this.$staticConfig.getAdbFilePath(), args: ["-s", deviceId, "forward", "--remove", `tcp:${port}`] });
            return port;
        });
    }
    unixSocketForward(local, remote) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.device.adb.executeCommand(["forward", `tcp:${local}`, `localabstract:${remote}`]);
        });
    }
    debugCore(appId, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            const result = { debugUrl: null };
            if (debugOptions.stop) {
                yield this.removePortForwarding();
                return result;
            }
            yield this.validateRunningApp(this.deviceIdentifier, appId);
            if (debugOptions.debugBrk) {
                yield this.waitForDebugServer(appId);
            }
            const debugPort = yield this.getForwardedDebugPort(this.deviceIdentifier, appId);
            yield this.printDebugPort(this.deviceIdentifier, debugPort);
            result.debugUrl = this.getChromeDebugUrl(debugOptions, debugPort);
            return result;
        });
    }
    printDebugPort(deviceId, port) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$logger.info("device: " + deviceId + " debug port: " + port + "\n");
        });
    }
    validateRunningApp(deviceId, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!(yield this.isAppRunning(packageName, deviceId))) {
                this.$errors.failWithoutHelp(`The application ${packageName} does not appear to be running on ${deviceId} or is not built with debugging enabled. Try starting the application manually.`);
            }
        });
    }
    waitForDebugServer(appId) {
        return __awaiter(this, void 0, void 0, function* () {
            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 = yield this.device.adb.executeShellCommand(["ls", "-s", debuggerStartedFilePath]);
                maxWait--;
                debuggerStarted = forwardsResult.indexOf(waitText) === -1;
                if (!debuggerStarted) {
                    yield helpers_1.sleep(500);
                }
            }
            if (debuggerStarted) {
                this.$logger.info("# NativeScript Debugger started #");
            }
            else {
                this.$logger.warn("# NativeScript Debugger did not start in time #");
            }
        });
    }
    isAppRunning(appIdentifier, deviceIdentifier) {
        return __awaiter(this, void 0, void 0, function* () {
            const debuggableApps = yield this.$androidProcessService.getDebuggableApps(deviceIdentifier);
            return !!_.find(debuggableApps, a => a.appIdentifier === appIdentifier);
        });
    }
}
__decorate([
    decorators_1.performanceLog()
], AndroidDeviceDebugService.prototype, "debug", null);
__decorate([
    decorators_1.performanceLog()
], AndroidDeviceDebugService.prototype, "debugCore", null);
exports.AndroidDeviceDebugService = AndroidDeviceDebugService;
$injector.register("androidDeviceDebugService", AndroidDeviceDebugService, false);
