"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const log4js = require("log4js");
const debug_service_base_1 = require("./debug-service-base");
const constants_1 = require("../common/constants");
const constants_2 = require("../constants");
const helpers_1 = require("../common/helpers");
const inspectorAppName = "NativeScript Inspector.app";
const inspectorNpmPackageName = "tns-ios-inspector";
const inspectorUiDir = "WebInspectorUI/";
class IOSDeviceDebugService extends debug_service_base_1.DebugServiceBase {
    constructor(device, $devicesService, $platformService, $iOSEmulatorServices, $childProcess, $hostInfo, $logger, $errors, $packageInstallationManager, $iOSDebuggerPortService, $processService, $appDebugSocketProxyFactory, $projectDataService, $deviceLogProvider) {
        super(device, $devicesService);
        this.device = device;
        this.$devicesService = $devicesService;
        this.$platformService = $platformService;
        this.$iOSEmulatorServices = $iOSEmulatorServices;
        this.$childProcess = $childProcess;
        this.$hostInfo = $hostInfo;
        this.$logger = $logger;
        this.$errors = $errors;
        this.$packageInstallationManager = $packageInstallationManager;
        this.$iOSDebuggerPortService = $iOSDebuggerPortService;
        this.$processService = $processService;
        this.$appDebugSocketProxyFactory = $appDebugSocketProxyFactory;
        this.$projectDataService = $projectDataService;
        this.$deviceLogProvider = $deviceLogProvider;
        this.$processService.attachToProcessExitSignals(this, this.debugStop);
        this.$appDebugSocketProxyFactory.on(constants_2.CONNECTION_ERROR_EVENT_NAME, (e) => this.emit(constants_2.CONNECTION_ERROR_EVENT_NAME, e));
        this.deviceIdentifier = this.device.deviceInfo.identifier;
    }
    get platform() {
        return "ios";
    }
    debug(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            this.validateOptions(debugOptions);
            yield this.startDeviceLogProcess(debugData, debugOptions);
            yield this.$iOSDebuggerPortService.attachToDebuggerPortFoundEvent(this.device, debugData, debugOptions);
            if (!debugOptions.start) {
                yield this.startApp(debugData, debugOptions);
            }
            return this.wireDebuggerClient(debugData, debugOptions);
        });
    }
    debugStart(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.startApp(debugData, debugOptions);
            yield this.wireDebuggerClient(debugData, debugOptions);
        });
    }
    debugStop() {
        return __awaiter(this, void 0, void 0, function* () {
            this.$appDebugSocketProxyFactory.removeAllProxies();
            yield this.stopAppDebuggerOnSimulator();
        });
    }
    getChromeDebugUrl(debugOptions, port) {
        const debugOpts = _.cloneDeep(debugOptions);
        debugOpts.useBundledDevTools = debugOpts.useBundledDevTools === undefined ? false : debugOpts.useBundledDevTools;
        const chromeDebugUrl = super.getChromeDebugUrl(debugOpts, port);
        return chromeDebugUrl;
    }
    startApp(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.device.isEmulator) {
                yield this.startAppOnSimulator(debugData, debugOptions);
            }
            else {
                yield this.startAppOnDevice(debugData, debugOptions);
            }
        });
    }
    validateOptions(debugOptions) {
        if (debugOptions.debugBrk && debugOptions.start) {
            this.$errors.failWithoutHelp("Expected exactly one of the --debug-brk or --start options.");
        }
    }
    startDeviceLogProcess(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            if (debugOptions.justlaunch) {
                this.$deviceLogProvider.muteLogsForDevice(this.deviceIdentifier);
            }
            let projectName = debugData.projectName;
            if (!projectName && debugData.projectDir) {
                const projectData = this.$projectDataService.getProjectData(debugData.projectDir);
                projectName = projectData.projectName;
            }
            if (projectName) {
                this.$deviceLogProvider.setProjectNameForDevice(this.deviceIdentifier, projectName);
            }
            yield this.device.openDeviceLogStream({ predicate: constants_1.IOS_LOG_PREDICATE });
        });
    }
    startAppOnSimulator(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            const args = debugOptions.debugBrk ? "--nativescript-debug-brk" : "--nativescript-debug-start";
            const launchResult = yield this.$iOSEmulatorServices.runApplicationOnEmulator(debugData.pathToAppPackage, {
                waitForDebugger: true,
                captureStdin: true,
                args: args,
                appId: debugData.applicationIdentifier,
                skipInstall: true,
                device: this.deviceIdentifier,
                justlaunch: debugOptions.justlaunch,
                timeout: debugOptions.timeout,
                sdk: debugOptions.sdk
            });
            const pid = helpers_1.getPidFromiOSSimulatorLogs(debugData.applicationIdentifier, launchResult);
            this.startAppDebuggerOnSimulator(pid);
        });
    }
    startAppOnDevice(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            const runOptions = {
                device: this.deviceIdentifier,
                emulator: this.device.isEmulator,
                justlaunch: debugOptions.justlaunch
            };
            const projectData = this.$projectDataService.getProjectData(debugData.projectDir);
            yield this.$platformService.startApplication(this.platform, runOptions, { appId: debugData.applicationIdentifier, projectName: projectData.projectName });
        });
    }
    startAppDebuggerOnSimulator(pid) {
        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");
    }
    stopAppDebuggerOnSimulator() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this._lldbProcess) {
                this._lldbProcess.stdin.write("process detach\n");
                yield this.killProcess(this._lldbProcess);
                this._lldbProcess = undefined;
            }
        });
    }
    killProcess(childProcess) {
        return __awaiter(this, void 0, void 0, function* () {
            if (childProcess) {
                return new Promise((resolve, reject) => {
                    childProcess.on("close", resolve);
                    childProcess.kill();
                });
            }
        });
    }
    wireDebuggerClient(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            if ((debugOptions.inspector || !debugOptions.client) && this.$hostInfo.isDarwin) {
                return yield this.setupTcpAppDebugProxy(debugData, debugOptions);
            }
            else {
                return yield this.setupWebAppDebugProxy(debugOptions, debugData);
            }
        });
    }
    setupWebAppDebugProxy(debugOptions, debugData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (debugOptions.chrome) {
                this.$logger.info("'--chrome' is the default behavior. Use --inspector to debug iOS applications using the Safari Web Inspector.");
            }
            const existingWebProxy = this.$appDebugSocketProxyFactory.getWebSocketProxy(this.deviceIdentifier, debugData.applicationIdentifier);
            const webSocketProxy = existingWebProxy || (yield this.$appDebugSocketProxyFactory.addWebSocketProxy(this.device, debugData.applicationIdentifier));
            return this.getChromeDebugUrl(debugOptions, webSocketProxy.options.port);
        });
    }
    setupTcpAppDebugProxy(debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            const existingTcpProxy = this.$appDebugSocketProxyFactory.getTCPSocketProxy(this.deviceIdentifier, debugData.applicationIdentifier);
            const tcpSocketProxy = existingTcpProxy || (yield this.$appDebugSocketProxyFactory.addTCPSocketProxy(this.device, debugData.applicationIdentifier));
            if (!existingTcpProxy) {
                const inspectorProcess = yield this.openAppInspector(tcpSocketProxy.address(), debugData, debugOptions);
                if (inspectorProcess) {
                    tcpSocketProxy.on("close", () => __awaiter(this, void 0, void 0, function* () {
                        yield this.killProcess(inspectorProcess);
                    }));
                }
            }
            return null;
        });
    }
    openAppInspector(fileDescriptor, debugData, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            if (debugOptions.client) {
                const inspectorPath = yield this.$packageInstallationManager.getInspectorFromCache(inspectorNpmPackageName, debugData.projectDir);
                const inspectorSourceLocation = path.join(inspectorPath, inspectorUiDir, "Main.html");
                const inspectorApplicationPath = path.join(inspectorPath, inspectorAppName, "Contents", "MacOS", inspectorAppName, "Contents", "MacOS", "NativeScript Inspector");
                const inspectorProcess = this.$childProcess.spawn(inspectorApplicationPath, [inspectorSourceLocation, debugData.projectName, fileDescriptor]);
                inspectorProcess.on("error", (e) => this.$logger.trace(e));
                return inspectorProcess;
            }
            else {
                this.$logger.info("Suppressing debugging client.");
                return null;
            }
        });
    }
}
exports.IOSDeviceDebugService = IOSDeviceDebugService;
$injector.register("iOSDeviceDebugService", IOSDeviceDebugService, false);
