"use strict";
const net = require("net");
const path = require("path");
const log4js = require("log4js");
const byline = require("byline");
const inspectorBackendPort = 18181;
const inspectorAppName = "NativeScript Inspector.app";
const inspectorNpmPackageName = "tns-ios-inspector";
const inspectorUiDir = "WebInspectorUI/";
const TIMEOUT_SECONDS = 9;
class IOSDebugService {
    constructor($config, $platformService, $iOSEmulatorServices, $devicesService, $platformsData, $projectData, $childProcess, $logger, $fs, $errors, $injector, $npmInstallationManager, $options, $utils, $iOSNotification, $iOSSocketRequestExecutor, $processService, $socketProxyFactory, $npm) {
        this.$config = $config;
        this.$platformService = $platformService;
        this.$iOSEmulatorServices = $iOSEmulatorServices;
        this.$devicesService = $devicesService;
        this.$platformsData = $platformsData;
        this.$projectData = $projectData;
        this.$childProcess = $childProcess;
        this.$logger = $logger;
        this.$fs = $fs;
        this.$errors = $errors;
        this.$injector = $injector;
        this.$npmInstallationManager = $npmInstallationManager;
        this.$options = $options;
        this.$utils = $utils;
        this.$iOSNotification = $iOSNotification;
        this.$iOSSocketRequestExecutor = $iOSSocketRequestExecutor;
        this.$processService = $processService;
        this.$socketProxyFactory = $socketProxyFactory;
        this.$npm = $npm;
        this._sockets = [];
        this.$processService.attachToProcessExitSignals(this, this.debugStop);
    }
    get platform() {
        return "ios";
    }
    debug() {
        if (this.$options.debugBrk && this.$options.start) {
            this.$errors.failWithoutHelp("Expected exactly one of the --debug-brk or --start options.");
        }
        if (this.$devicesService.isOnlyiOSSimultorRunning() || this.$devicesService.deviceCount === 0) {
            this.$options.emulator = true;
        }
        if (this.$options.emulator) {
            if (this.$options.debugBrk) {
                return this.emulatorDebugBrk(true);
            }
            else if (this.$options.start) {
                return this.emulatorStart();
            }
            else {
                return this.emulatorDebugBrk();
            }
        }
        else {
            if (this.$options.debugBrk) {
                return this.deviceDebugBrk(true);
            }
            else if (this.$options.start) {
                return this.deviceStart();
            }
            else {
                return this.deviceDebugBrk(false);
            }
        }
    }
    debugStart() {
        return (() => {
            this.$devicesService.initialize({ platform: this.platform, deviceId: this.$options.device }).wait();
            this.$devicesService.execute((device) => device.isEmulator ? this.emulatorDebugBrk() : this.debugBrkCore(device)).wait();
        }).future()();
    }
    debugStop() {
        return (() => {
            if (this._socketProxy) {
                this._socketProxy.close();
                this._socketProxy = null;
            }
            _.forEach(this._sockets, socket => socket.destroy());
            this._sockets = [];
            if (this._lldbProcess) {
                this._lldbProcess.stdin.write("process detach\n");
                this._lldbProcess.kill();
                this._lldbProcess = undefined;
            }
            if (this._childProcess) {
                this._childProcess.kill();
                this._childProcess = undefined;
            }
        }).future()();
    }
    emulatorDebugBrk(shouldBreak) {
        return (() => {
            let platformData = this.$platformsData.getPlatformData(this.platform);
            if (this.$options.rebuild) {
                this.$platformService.buildPlatform(this.platform).wait();
            }
            let emulatorPackage = this.$platformService.getLatestApplicationPackageForEmulator(platformData);
            let args = shouldBreak ? "--nativescript-debug-brk" : "--nativescript-debug-start";
            let child_process = this.$iOSEmulatorServices.runApplicationOnEmulator(emulatorPackage.packageName, {
                waitForDebugger: true, captureStdin: true,
                args: args, appId: this.$projectData.projectId,
                skipInstall: this.$config.debugLivesync
            }).wait();
            let lineStream = byline(child_process.stdout);
            this._childProcess = child_process;
            lineStream.on('data', (line) => {
                let lineText = line.toString();
                if (lineText && _.startsWith(lineText, this.$projectData.projectId)) {
                    let pid = _.trimStart(lineText, this.$projectData.projectId + ": ");
                    this._lldbProcess = this.$childProcess.spawn("lldb", ["-p", pid]);
                    if (log4js.levels.TRACE.isGreaterThanOrEqualTo(this.$logger.getLevel())) {
                        this._lldbProcess.stdout.pipe(process.stdout);
                    }
                    this._lldbProcess.stderr.pipe(process.stderr);
                    this._lldbProcess.stdin.write("process continue\n");
                }
                else {
                    process.stdout.write(line + "\n");
                }
            });
            this.wireDebuggerClient().wait();
        }).future()();
    }
    emulatorStart() {
        return (() => {
            this.wireDebuggerClient().wait();
            let attachRequestMessage = this.$iOSNotification.attachRequest;
            let iOSEmulator = this.$iOSEmulatorServices;
            iOSEmulator.postDarwinNotification(attachRequestMessage).wait();
        }).future()();
    }
    deviceDebugBrk(shouldBreak) {
        return (() => {
            this.$devicesService.initialize({ platform: this.platform, deviceId: this.$options.device }).wait();
            this.$devicesService.execute((device) => (() => {
                if (device.isEmulator) {
                    return this.emulatorDebugBrk(shouldBreak).wait();
                }
                let action;
                if (this.$config.debugLivesync) {
                    action = this.$platformService.runPlatform(this.platform);
                }
                else {
                    action = this.$platformService.deployPlatform(this.platform);
                }
                this.debugBrkCore(device, shouldBreak).wait();
                action.wait();
            }).future()()).wait();
        }).future()();
    }
    debugBrkCore(device, shouldBreak) {
        return (() => {
            let timeout = this.$utils.getMilliSecondsTimeout(TIMEOUT_SECONDS);
            this.$iOSSocketRequestExecutor.executeLaunchRequest(device, timeout, timeout, shouldBreak).wait();
            this.wireDebuggerClient(device).wait();
        }).future()();
    }
    deviceStart() {
        return (() => {
            this.$devicesService.initialize({ platform: this.platform, deviceId: this.$options.device }).wait();
            this.$devicesService.execute((device) => device.isEmulator ? this.emulatorStart() : this.deviceStartCore(device)).wait();
        }).future()();
    }
    deviceStartCore(device) {
        return (() => {
            let timeout = this.$utils.getMilliSecondsTimeout(TIMEOUT_SECONDS);
            this.$iOSSocketRequestExecutor.executeAttachRequest(device, timeout).wait();
            this.wireDebuggerClient(device).wait();
        }).future()();
    }
    wireDebuggerClient(device) {
        return (() => {
            let factory = () => {
                let socket = device ? device.connectToPort(inspectorBackendPort) : net.connect(inspectorBackendPort);
                this._sockets.push(socket);
                return socket;
            };
            if (this.$options.chrome) {
                this._socketProxy = this.$socketProxyFactory.createWebSocketProxy(factory);
                this.$logger.info(`To start debugging, open the following URL in Chrome:\nchrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=localhost:${this._socketProxy.options.port}\n`);
            }
            else {
                this._socketProxy = this.$socketProxyFactory.createTCPSocketProxy(factory);
                this.openAppInspector(this._socketProxy.address()).wait();
            }
        }).future()();
    }
    openAppInspector(fileDescriptor) {
        if (this.$options.client) {
            return (() => {
                let inspectorPath = this.$npmInstallationManager.getInspectorFromCache(inspectorNpmPackageName, this.$projectData.projectDir).wait();
                let inspectorSourceLocation = path.join(inspectorPath, inspectorUiDir, "Main.html");
                let inspectorApplicationPath = path.join(inspectorPath, inspectorAppName);
                let cmd = `open -a '${inspectorApplicationPath}' --args '${inspectorSourceLocation}' '${this.$projectData.projectName}' '${fileDescriptor}'`;
                this.$childProcess.exec(cmd).wait();
            }).future()();
        }
        else {
            return (() => {
                this.$logger.info("Suppressing debugging client.");
            }).future()();
        }
    }
}
$injector.register("iOSDebugService", IOSDebugService);
