"use strict";
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());
    });
};
const net = require("net");
const os = require("os");
const helpers_1 = require("../common/helpers");
class AndroidDebugService {
    constructor($devicesService, $platformService, $platformsData, $projectData, $logger, $options, $errors, $config, $androidDeviceDiscovery) {
        this.$devicesService = $devicesService;
        this.$platformService = $platformService;
        this.$platformsData = $platformsData;
        this.$projectData = $projectData;
        this.$logger = $logger;
        this.$options = $options;
        this.$errors = $errors;
        this.$config = $config;
        this.$androidDeviceDiscovery = $androidDeviceDiscovery;
        this._device = null;
    }
    get platform() {
        return "android";
    }
    get device() {
        return this._device;
    }
    set device(newDevice) {
        this._device = newDevice;
    }
    debug() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.$options.emulator
                ? this.debugOnEmulator()
                : this.debugOnDevice();
        });
    }
    debugOnEmulator() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.$androidDeviceDiscovery.startLookingForDevices();
            yield this.debugOnDevice();
        });
    }
    isPortAvailable(candidatePort) {
        return new Promise((resolve, reject) => {
            let isResolved = false;
            let server = net.createServer();
            server.on("error", (err) => {
                if (!isResolved) {
                    isResolved = true;
                    resolve(false);
                }
            });
            server.once("close", () => {
                if (!isResolved) {
                    isResolved = true;
                    resolve(true);
                }
            });
            server.on("listening", (err) => {
                if (err && !isResolved) {
                    isResolved = true;
                    resolve(false);
                }
                server.close();
            });
            server.listen(candidatePort, "localhost");
        });
    }
    getForwardedLocalDebugPortForPackageName(deviceId, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            let port = -1;
            let forwardsResult = yield this.device.adb.executeCommand(["forward", "--list"]);
            let unixSocketName = `${packageName}-inspectorServer`;
            let regexp = new RegExp(`(?:${deviceId} tcp:)([\\d]+)(?= localabstract:${unixSocketName})`, "g");
            let match = regexp.exec(forwardsResult);
            if (match) {
                port = parseInt(match[1]);
            }
            else {
                let candidatePort = 40000;
                for (; !(yield this.isPortAvailable(candidatePort)); ++candidatePort) {
                    if (candidatePort > 65534) {
                        this.$errors.failWithoutHelp("Unable to find free local port.");
                    }
                }
                port = candidatePort;
                yield this.unixSocketForward(port, `${unixSocketName}`);
            }
            return port;
        });
    }
    unixSocketForward(local, remote) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.device.adb.executeCommand(["forward", `tcp:${local}`, `localabstract:${remote}`]);
        });
    }
    debugOnDevice() {
        return __awaiter(this, void 0, void 0, function* () {
            let packageFile = "";
            if (!this.$options.start && !this.$options.emulator) {
                let cachedDeviceOption = this.$options.forDevice;
                this.$options.forDevice = !!cachedDeviceOption;
                let platformData = this.$platformsData.getPlatformData(this.platform);
                packageFile = this.$platformService.getLatestApplicationPackageForDevice(platformData).packageName;
                this.$logger.out("Using ", packageFile);
            }
            yield this.$devicesService.initialize({ platform: this.platform, deviceId: this.$options.device });
            let action = (device) => this.debugCore(device, packageFile, this.$projectData.projectId);
            yield this.$devicesService.execute(action);
        });
    }
    debugCore(device, packageFile, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            this.device = device;
            yield this.printDebugPort(device.deviceInfo.identifier, packageName);
            if (this.$options.start) {
                yield this.attachDebugger(device.deviceInfo.identifier, packageName);
            }
            else if (this.$options.stop) {
                yield this.detachDebugger(packageName);
            }
            else {
                yield this.startAppWithDebugger(packageFile, packageName);
                yield this.attachDebugger(device.deviceInfo.identifier, packageName);
            }
        });
    }
    printDebugPort(deviceId, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            let port = yield this.getForwardedLocalDebugPortForPackageName(deviceId, packageName);
            this.$logger.info("device: " + deviceId + " debug port: " + port + "\n");
        });
    }
    attachDebugger(deviceId, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            let startDebuggerCommand = ["am", "broadcast", "-a", `\"${packageName}-debug\"`, "--ez", "enable", "true"];
            yield this.device.adb.executeShellCommand(startDebuggerCommand);
            if (this.$options.client) {
                let port = yield this.getForwardedLocalDebugPortForPackageName(deviceId, packageName);
                this.startDebuggerClient(port);
            }
        });
    }
    detachDebugger(packageName) {
        return this.device.adb.executeShellCommand(["am", "broadcast", "-a", `${packageName}-debug`, "--ez", "enable", "false"]);
    }
    startAppWithDebugger(packageFile, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.$options.emulator && !this.$config.debugLivesync) {
                yield this.device.applicationManager.uninstallApplication(packageName);
                yield this.device.applicationManager.installApplication(packageFile);
            }
            yield this.debugStartCore();
        });
    }
    debugStart() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.$devicesService.initialize({ platform: this.platform, deviceId: this.$options.device });
            let action = (device) => {
                this.device = device;
                return this.debugStartCore();
            };
            yield this.$devicesService.execute(action);
        });
    }
    debugStop() {
        return __awaiter(this, void 0, void 0, function* () {
            this.stopDebuggerClient();
            return;
        });
    }
    debugStartCore() {
        return __awaiter(this, void 0, void 0, function* () {
            let packageName = this.$projectData.projectId;
            yield this.device.applicationManager.stopApplication(packageName);
            if (this.$options.debugBrk) {
                yield this.device.adb.executeShellCommand([`cat /dev/null > /data/local/tmp/${packageName}-debugbreak`]);
            }
            yield this.device.adb.executeShellCommand([`cat /dev/null > /data/local/tmp/${packageName}-debugger-started`]);
            yield this.device.applicationManager.startApplication(packageName);
            yield this.waitForDebugger(packageName);
        });
    }
    waitForDebugger(packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            let waitText = `0 /data/local/tmp/${packageName}-debugger-started`;
            let maxWait = 12;
            let debugerStarted = false;
            while (maxWait > 0 && !debugerStarted) {
                let forwardsResult = yield this.device.adb.executeShellCommand(["ls", "-s", `/data/local/tmp/${packageName}-debugger-started`]);
                maxWait--;
                debugerStarted = forwardsResult.indexOf(waitText) === -1;
                if (!debugerStarted) {
                    helpers_1.sleep(500);
                }
            }
            if (debugerStarted) {
                this.$logger.info("# NativeScript Debugger started #");
            }
            else {
                this.$logger.warn("# NativeScript Debugger did not start in time #");
            }
        });
    }
    startDebuggerClient(port) {
        this.$logger.info(`To start debugging, open the following URL in Chrome:${os.EOL}chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=localhost:${port}${os.EOL}`.cyan);
    }
    stopDebuggerClient() {
        if (this._debuggerClientProcess) {
            this._debuggerClientProcess.kill();
            this._debuggerClientProcess = null;
        }
    }
}
$injector.register("androidDebugService", AndroidDebugService);
