"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IOSDeviceDebugService = void 0;
const path = require("path");
const debug_service_base_1 = require("./debug-service-base");
const constants_1 = require("../constants");
const inspectorAppName = "NativeScript Inspector.app";
const inspectorNpmPackageName = "tns-ios-inspector";
const inspectorUiDir = "WebInspectorUI/";
const decorators_1 = require("../common/decorators");
const os_1 = require("os");
const yok_1 = require("../common/yok");
class IOSDeviceDebugService extends debug_service_base_1.DebugServiceBase {
    constructor(device, $devicesService, $childProcess, $hostInfo, $logger, $errors, $packageInstallationManager, $appDebugSocketProxyFactory, $projectDataService) {
        super(device, $devicesService);
        this.device = device;
        this.$devicesService = $devicesService;
        this.$childProcess = $childProcess;
        this.$hostInfo = $hostInfo;
        this.$logger = $logger;
        this.$errors = $errors;
        this.$packageInstallationManager = $packageInstallationManager;
        this.$appDebugSocketProxyFactory = $appDebugSocketProxyFactory;
        this.$projectDataService = $projectDataService;
        this.$appDebugSocketProxyFactory.on(constants_1.CONNECTION_ERROR_EVENT_NAME, (e) => this.emit(constants_1.CONNECTION_ERROR_EVENT_NAME, e));
        this.deviceIdentifier = this.device.deviceInfo.identifier;
    }
    get platform() {
        return "ios";
    }
    async debug(debugData, debugOptions) {
        await this.validateOptions(debugOptions);
        const result = { debugUrl: null };
        result.debugUrl = await this.wireDebuggerClient(debugData, debugOptions);
        return result;
    }
    async debugStop() {
        this.$appDebugSocketProxyFactory.removeAllProxies();
    }
    async validateOptions(debugOptions) {
        if (!this.$hostInfo.isWindows && !this.$hostInfo.isDarwin) {
            this.$errors.fail(`Debugging on iOS devices is not supported for ${(0, os_1.platform)()} yet.`);
        }
        if (debugOptions.debugBrk && debugOptions.start) {
            this.$errors.fail("Expected exactly one of the --debug-brk or --start options.");
        }
        await this.validateUSBConnectedDevice();
    }
    async validateUSBConnectedDevice() {
        const device = await this.$devicesService.getDevice(this.deviceIdentifier);
        if (device.deviceInfo.connectionTypes.indexOf(constants_1.DeviceConnectionType.USB) ===
            -1 &&
            device.deviceInfo.connectionTypes.indexOf(constants_1.DeviceConnectionType.Local) ===
                -1) {
            const deviceConnectionTypes = device.deviceInfo.connectionTypes
                .map((type) => constants_1.DeviceConnectionType[type])
                .join(", ");
            this.$errors.fail(`Debugging application requires a USB or LOCAL connection while the target device "${this.deviceIdentifier}" has connection type "${deviceConnectionTypes}".`);
        }
    }
    getProjectName(debugData) {
        let projectName = debugData.projectName;
        if (!projectName && debugData.projectDir) {
            const projectData = this.$projectDataService.getProjectData(debugData.projectDir);
            projectName = projectData.projectName;
        }
        return projectName;
    }
    async killProcess(childProcess) {
        if (childProcess) {
            return new Promise((resolve, reject) => {
                childProcess.on("close", resolve);
                childProcess.kill();
            });
        }
    }
    async wireDebuggerClient(debugData, debugOptions) {
        if ((debugOptions.inspector || !debugOptions.client) &&
            this.$hostInfo.isDarwin) {
            return await this.setupTcpAppDebugProxy(debugData, debugOptions);
        }
        else {
            return await this.setupWebAppDebugProxy(debugOptions, debugData);
        }
    }
    async setupWebAppDebugProxy(debugOptions, debugData) {
        if (debugOptions.chrome) {
            this.$logger.info("'--chrome' is the default behavior. Use --inspector to debug iOS applications using the Safari Web Inspector.");
        }
        const projectName = this.getProjectName(debugData);
        const webSocketProxy = await this.$appDebugSocketProxyFactory.ensureWebSocketProxy(this.device, debugData.applicationIdentifier, projectName, debugData.projectDir);
        return this.getChromeDebugUrl(debugOptions, webSocketProxy.options.port);
    }
    async setupTcpAppDebugProxy(debugData, debugOptions) {
        const projectName = this.getProjectName(debugData);
        const existingTcpProxy = this.$appDebugSocketProxyFactory.getTCPSocketProxy(this.deviceIdentifier, debugData.applicationIdentifier);
        const tcpSocketProxy = existingTcpProxy ||
            (await this.$appDebugSocketProxyFactory.addTCPSocketProxy(this.device, debugData.applicationIdentifier, projectName, debugData.projectDir));
        if (!existingTcpProxy) {
            const inspectorProcess = await this.openAppInspector(tcpSocketProxy.address(), debugData, debugOptions);
            if (inspectorProcess) {
                tcpSocketProxy.on("close", async () => {
                    await this.killProcess(inspectorProcess);
                });
            }
        }
        return null;
    }
    async openAppInspector(fileDescriptor, debugData, debugOptions) {
        if (debugOptions.client) {
            const inspectorPath = await 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;
__decorate([
    (0, decorators_1.performanceLog)()
], IOSDeviceDebugService.prototype, "debug", null);
__decorate([
    (0, decorators_1.performanceLog)()
], IOSDeviceDebugService.prototype, "wireDebuggerClient", null);
__decorate([
    (0, decorators_1.performanceLog)()
], IOSDeviceDebugService.prototype, "openAppInspector", null);
yok_1.injector.register("iOSDeviceDebugService", IOSDeviceDebugService, false);
