"use strict";
var net = require("net");
var path = require("path");
var log4js = require("log4js");
var byline = require("byline");
var inspectorBackendPort = 18181;
var inspectorAppName = "NativeScript Inspector.app";
var inspectorNpmPackageName = "tns-ios-inspector";
var inspectorUiDir = "WebInspectorUI/";
var TIMEOUT_SECONDS = 9;
var IOSDebugService = (function () {
    function IOSDebugService($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);
    }
    Object.defineProperty(IOSDebugService.prototype, "platform", {
        get: function () {
            return "ios";
        },
        enumerable: true,
        configurable: true
    });
    IOSDebugService.prototype.debug = function () {
        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);
            }
        }
    };
    IOSDebugService.prototype.debugStart = function () {
        var _this = this;
        return (function () {
            _this.$devicesService.initialize({ platform: _this.platform, deviceId: _this.$options.device }).wait();
            _this.$devicesService.execute(function (device) { return device.isEmulator ? _this.emulatorDebugBrk() : _this.debugBrkCore(device); }).wait();
        }).future()();
    };
    IOSDebugService.prototype.debugStop = function () {
        var _this = this;
        return (function () {
            if (_this._socketProxy) {
                _this._socketProxy.close();
                _this._socketProxy = null;
            }
            _.forEach(_this._sockets, function (socket) { return 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()();
    };
    IOSDebugService.prototype.emulatorDebugBrk = function (shouldBreak) {
        var _this = this;
        return (function () {
            var platformData = _this.$platformsData.getPlatformData(_this.platform);
            if (_this.$options.rebuild) {
                _this.$platformService.prepareAndBuild(_this.platform).wait();
            }
            var emulatorPackage = _this.$platformService.getLatestApplicationPackageForEmulator(platformData).wait();
            var args = shouldBreak ? "--nativescript-debug-brk" : "--nativescript-debug-start";
            var child_process = _this.$iOSEmulatorServices.runApplicationOnEmulator(emulatorPackage.packageName, {
                waitForDebugger: true, captureStdin: true,
                args: args, appId: _this.$projectData.projectId,
                skipInstall: _this.$config.debugLivesync
            }).wait();
            var lineStream = byline(child_process.stdout);
            _this._childProcess = child_process;
            lineStream.on('data', function (line) {
                var lineText = line.toString();
                if (lineText && _.startsWith(lineText, _this.$projectData.projectId)) {
                    var 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()();
    };
    IOSDebugService.prototype.emulatorStart = function () {
        var _this = this;
        return (function () {
            _this.wireDebuggerClient().wait();
            var attachRequestMessage = _this.$iOSNotification.attachRequest;
            var iOSEmulator = _this.$iOSEmulatorServices;
            iOSEmulator.postDarwinNotification(attachRequestMessage).wait();
        }).future()();
    };
    IOSDebugService.prototype.deviceDebugBrk = function (shouldBreak) {
        var _this = this;
        return (function () {
            _this.$devicesService.initialize({ platform: _this.platform, deviceId: _this.$options.device }).wait();
            _this.$devicesService.execute(function (device) { return (function () {
                if (device.isEmulator) {
                    return _this.emulatorDebugBrk(shouldBreak).wait();
                }
                var action;
                if (_this.$config.debugLivesync) {
                    action = _this.$platformService.startOnDevice(_this.platform);
                }
                else {
                    action = _this.$platformService.deployOnDevice(_this.platform);
                }
                _this.debugBrkCore(device, shouldBreak).wait();
                action.wait();
            }).future()(); }).wait();
        }).future()();
    };
    IOSDebugService.prototype.debugBrkCore = function (device, shouldBreak) {
        var _this = this;
        return (function () {
            var timeout = _this.$utils.getMilliSecondsTimeout(TIMEOUT_SECONDS);
            _this.$iOSSocketRequestExecutor.executeLaunchRequest(device, timeout, timeout, shouldBreak).wait();
            _this.wireDebuggerClient(device).wait();
        }).future()();
    };
    IOSDebugService.prototype.deviceStart = function () {
        var _this = this;
        return (function () {
            _this.$devicesService.initialize({ platform: _this.platform, deviceId: _this.$options.device }).wait();
            _this.$devicesService.execute(function (device) { return device.isEmulator ? _this.emulatorStart() : _this.deviceStartCore(device); }).wait();
        }).future()();
    };
    IOSDebugService.prototype.deviceStartCore = function (device) {
        var _this = this;
        return (function () {
            var timeout = _this.$utils.getMilliSecondsTimeout(TIMEOUT_SECONDS);
            _this.$iOSSocketRequestExecutor.executeAttachRequest(device, timeout).wait();
            _this.wireDebuggerClient(device).wait();
        }).future()();
    };
    IOSDebugService.prototype.wireDebuggerClient = function (device) {
        var _this = this;
        return (function () {
            var factory = function () {
                var 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()();
    };
    IOSDebugService.prototype.openAppInspector = function (fileDescriptor) {
        var _this = this;
        if (this.$options.client) {
            return (function () {
                var inspectorPath = _this.$npmInstallationManager.getInspectorFromCache(inspectorNpmPackageName, _this.$projectData.projectDir).wait();
                var inspectorSourceLocation = path.join(inspectorPath, inspectorUiDir, "Main.html");
                var inspectorApplicationPath = path.join(inspectorPath, inspectorAppName);
                var cmd = "open -a '" + inspectorApplicationPath + "' --args '" + inspectorSourceLocation + "' '" + _this.$projectData.projectName + "' '" + fileDescriptor + "'";
                _this.$childProcess.exec(cmd).wait();
            }).future()();
        }
        else {
            return (function () {
                _this.$logger.info("Suppressing debugging client.");
            }).future()();
        }
    };
    return IOSDebugService;
}());
$injector.register("iOSDebugService", IOSDebugService);
