"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;
};
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 decorators_1 = require("../common/decorators");
const os_1 = require("os");
const url_1 = require("url");
const constants_1 = require("../common/constants");
const constants_2 = require("../constants");
const events_1 = require("events");
class DebugController extends events_1.EventEmitter {
    constructor($analyticsService, $debugDataService, $devicesService, $errors, $injector, $liveSyncProcessDataService, $logger, $mobileHelper, $projectDataService) {
        super();
        this.$analyticsService = $analyticsService;
        this.$debugDataService = $debugDataService;
        this.$devicesService = $devicesService;
        this.$errors = $errors;
        this.$injector = $injector;
        this.$liveSyncProcessDataService = $liveSyncProcessDataService;
        this.$logger = $logger;
        this.$mobileHelper = $mobileHelper;
        this.$projectDataService = $projectDataService;
        this._platformDebugServices = {};
    }
    startDebug(debugData) {
        return __awaiter(this, void 0, void 0, function* () {
            const { debugOptions: options } = debugData;
            const device = this.$devicesService.getDeviceByIdentifier(debugData.deviceIdentifier);
            if (!device) {
                this.$errors.failWithoutHelp(`Cannot find device with identifier ${debugData.deviceIdentifier}.`);
            }
            if (device.deviceInfo.status !== constants_1.CONNECTED_STATUS) {
                this.$errors.failWithoutHelp(`The device with identifier ${debugData.deviceIdentifier} is unreachable. Make sure it is Trusted and try again.`);
            }
            yield this.$analyticsService.trackEventActionInGoogleAnalytics({
                action: "Debug",
                device,
                additionalData: this.$mobileHelper.isiOSPlatform(device.deviceInfo.platform) && options && options.inspector ? "Inspector" : "Chrome",
                projectDir: debugData.projectDir
            });
            if (!(yield device.applicationManager.isApplicationInstalled(debugData.applicationIdentifier))) {
                this.$errors.failWithoutHelp(`The application ${debugData.applicationIdentifier} is not installed on device with identifier ${debugData.deviceIdentifier}.`);
            }
            const debugService = this.getDeviceDebugService(device);
            if (!debugService) {
                this.$errors.failWithoutHelp(`Unsupported device OS: ${device.deviceInfo.platform}. You can debug your applications only on iOS or Android.`);
            }
            const debugOptions = _.cloneDeep(options);
            const debugResultInfo = yield debugService.debug(debugData, debugOptions);
            return this.getDebugInformation(debugResultInfo, device.deviceInfo.identifier);
        });
    }
    enableDebugging(enableDebuggingData) {
        const { deviceIdentifiers } = enableDebuggingData;
        return _.map(deviceIdentifiers, deviceIdentifier => this.enableDebuggingCore(enableDebuggingData.projectDir, deviceIdentifier, enableDebuggingData.debugOptions));
    }
    disableDebugging(disableDebuggingData) {
        return __awaiter(this, void 0, void 0, function* () {
            const { deviceIdentifiers, projectDir } = disableDebuggingData;
            for (const deviceIdentifier of deviceIdentifiers) {
                const liveSyncProcessInfo = this.$liveSyncProcessDataService.getPersistedData(projectDir);
                if (liveSyncProcessInfo.currentSyncAction) {
                    yield liveSyncProcessInfo.currentSyncAction;
                }
                const currentDeviceDescriptor = this.getDeviceDescriptor(projectDir, deviceIdentifier);
                if (currentDeviceDescriptor) {
                    currentDeviceDescriptor.debuggingEnabled = false;
                }
                else {
                    this.$errors.failWithoutHelp(`Couldn't disable debugging for ${deviceIdentifier}`);
                }
                const currentDevice = this.$devicesService.getDeviceByIdentifier(currentDeviceDescriptor.identifier);
                if (!currentDevice) {
                    this.$errors.failWithoutHelp(`Couldn't disable debugging for ${deviceIdentifier}. Could not find device.`);
                }
                yield this.stopDebug(currentDevice.deviceInfo.identifier);
                this.emit(constants_2.DEBUGGER_DETACHED_EVENT_NAME, { deviceIdentifier });
            }
        });
    }
    attachDebugger(attachDebuggerData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (attachDebuggerData.debugOptions) {
                attachDebuggerData.debugOptions.chrome = attachDebuggerData.debugOptions.chrome === undefined ? true : attachDebuggerData.debugOptions.chrome;
                attachDebuggerData.debugOptions.start = attachDebuggerData.debugOptions.start === undefined ? true : attachDebuggerData.debugOptions.start;
            }
            else {
                attachDebuggerData.debugOptions = {
                    chrome: true,
                    start: true
                };
            }
            const projectData = this.$projectDataService.getProjectData(attachDebuggerData.projectDir);
            const debugData = this.$debugDataService.getDebugData(attachDebuggerData.deviceIdentifier, projectData, attachDebuggerData.debugOptions);
            const debugInfo = yield this.startDebug(debugData);
            const result = this.printDebugInformation(debugInfo, attachDebuggerData.debugOptions.forceDebuggerAttachedEvent);
            return result;
        });
    }
    enableDebuggingCoreWithoutWaitingCurrentAction(projectDir, deviceIdentifier, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            const deviceDescriptor = this.getDeviceDescriptor(projectDir, deviceIdentifier);
            if (!deviceDescriptor) {
                this.$errors.failWithoutHelp(`Couldn't enable debugging for ${deviceIdentifier}`);
            }
            deviceDescriptor.debuggingEnabled = true;
            deviceDescriptor.debugOptions = debugOptions;
            const currentDeviceInstance = this.$devicesService.getDeviceByIdentifier(deviceIdentifier);
            const attachDebuggerData = {
                deviceIdentifier,
                isEmulator: currentDeviceInstance.isEmulator,
                outputPath: deviceDescriptor.outputPath,
                platform: currentDeviceInstance.deviceInfo.platform,
                projectDir,
                debugOptions
            };
            let debugInformation;
            try {
                debugInformation = yield this.attachDebugger(attachDebuggerData);
            }
            catch (err) {
                this.$logger.trace("Couldn't attach debugger, will modify options and try again.", err);
                attachDebuggerData.debugOptions.start = false;
                try {
                    debugInformation = yield this.attachDebugger(attachDebuggerData);
                }
                catch (innerErr) {
                    this.$logger.trace("Couldn't attach debugger with modified options.", innerErr);
                    throw err;
                }
            }
            return debugInformation;
        });
    }
    printDebugInformation(debugInformation, fireDebuggerAttachedEvent = true) {
        if (!!debugInformation.url) {
            if (fireDebuggerAttachedEvent) {
                this.emit(constants_2.DEBUGGER_ATTACHED_EVENT_NAME, debugInformation);
            }
            this.$logger.info(`To start debugging, open the following URL in Chrome:${os_1.EOL}${debugInformation.url}${os_1.EOL}`.cyan);
        }
        return debugInformation;
    }
    stopDebug(deviceIdentifier) {
        return __awaiter(this, void 0, void 0, function* () {
            const device = this.$devicesService.getDeviceByIdentifier(deviceIdentifier);
            const debugService = this.getDeviceDebugService(device);
            yield debugService.debugStop();
        });
    }
    getDeviceDescriptor(projectDir, deviceIdentifier) {
        const deviceDescriptors = this.$liveSyncProcessDataService.getDeviceDescriptors(projectDir);
        const currentDeviceDescriptor = _.find(deviceDescriptors, d => d.identifier === deviceIdentifier);
        return currentDeviceDescriptor;
    }
    getDeviceDebugService(device) {
        if (!this._platformDebugServices[device.deviceInfo.identifier]) {
            const devicePlatform = device.deviceInfo.platform;
            if (this.$mobileHelper.isiOSPlatform(devicePlatform)) {
                this._platformDebugServices[device.deviceInfo.identifier] = this.$injector.resolve("iOSDeviceDebugService", { device });
            }
            else if (this.$mobileHelper.isAndroidPlatform(devicePlatform)) {
                this._platformDebugServices[device.deviceInfo.identifier] = this.$injector.resolve("androidDeviceDebugService", { device });
            }
            else {
                this.$errors.failWithoutHelp(constants_2.DebugCommandErrors.UNSUPPORTED_DEVICE_OS_FOR_DEBUGGING);
            }
            this.attachConnectionErrorHandlers(this._platformDebugServices[device.deviceInfo.identifier]);
        }
        return this._platformDebugServices[device.deviceInfo.identifier];
    }
    attachConnectionErrorHandlers(platformDebugService) {
        let connectionErrorHandler = (e) => this.emit(constants_2.CONNECTION_ERROR_EVENT_NAME, e);
        connectionErrorHandler = connectionErrorHandler.bind(this);
        platformDebugService.on(constants_2.CONNECTION_ERROR_EVENT_NAME, connectionErrorHandler);
    }
    getDebugInformation(debugResultInfo, deviceIdentifier) {
        const debugInfo = {
            url: debugResultInfo.debugUrl,
            port: 0,
            deviceIdentifier
        };
        if (debugResultInfo.debugUrl) {
            const parseQueryString = true;
            const wsQueryParam = url_1.parse(debugResultInfo.debugUrl, parseQueryString).query.ws;
            const hostPortSplit = wsQueryParam && wsQueryParam.split(":");
            debugInfo.port = hostPortSplit && +hostPortSplit[1];
        }
        return debugInfo;
    }
    enableDebuggingCore(projectDir, deviceIdentifier, debugOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            const liveSyncProcessInfo = this.$liveSyncProcessDataService.getPersistedData(projectDir);
            if (liveSyncProcessInfo && liveSyncProcessInfo.currentSyncAction) {
                yield liveSyncProcessInfo.currentSyncAction;
            }
            return this.enableDebuggingCoreWithoutWaitingCurrentAction(projectDir, deviceIdentifier, debugOptions);
        });
    }
}
__decorate([
    decorators_1.performanceLog()
], DebugController.prototype, "startDebug", null);
__decorate([
    decorators_1.performanceLog()
], DebugController.prototype, "enableDebuggingCoreWithoutWaitingCurrentAction", null);
exports.DebugController = DebugController;
$injector.register("debugController", DebugController);
