/*---------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*/
"use strict";
const vscode_debugadapter_1 = require("vscode-debugadapter");
const utils = require("../utils");
const telemetry = require("../telemetry");
const chromeUtils = require("./chromeUtils");
const nls = require("vscode-nls");
const localize = nls.config(process.env.VSCODE_NLS_CONFIG)();
exports.getChromeTargetWebSocketURL = (address, port, targetFilter, targetUrl) => {
    // Take the custom targetFilter, default to taking all targets
    targetFilter = targetFilter || (target => true);
    return _getTargets(address, port, targetFilter).then(targets => {
        telemetry.reportEvent('targetCount', { numTargets: targets.length });
        if (!targets.length) {
            return utils.errP(localize('attach.responseButNoTargets', "Got a response from the target app, but no target pages found"));
        }
        const target = _selectTarget(targets, targetUrl);
        vscode_debugadapter_1.logger.verbose(`Attaching to target: ${JSON.stringify(target)}`);
        const wsUrl = target.webSocketDebuggerUrl;
        vscode_debugadapter_1.logger.verbose(`WebSocket Url: ${wsUrl}`);
        return wsUrl;
    });
};
function _getTargets(address, port, targetFilter) {
    const url = `http://${address}:${port}/json`;
    vscode_debugadapter_1.logger.log(`Discovering targets via ${url}`);
    return utils.getURL(url).then(jsonResponse => {
        try {
            const responseArray = JSON.parse(jsonResponse);
            if (Array.isArray(responseArray)) {
                return responseArray
                    .map(target => _fixRemoteUrl(address, target))
                    .filter(targetFilter);
            }
        }
        catch (e) {
        }
        return utils.errP(localize('attach.invalidResponse', "Response from the target seems invalid: {0}", jsonResponse));
    }, e => {
        return utils.errP(localize('attach.cannotConnect', "Cannot connect to the target: {0}", e.message));
    });
}
function _selectTarget(targets, targetUrl) {
    // If a url was specified, try to filter to that url
    let filteredTargets = targetUrl ?
        chromeUtils.getMatchingTargets(targets, targetUrl) :
        targets;
    if (!filteredTargets.length) {
        throw new Error(localize('attach.noMatchingTarget', "Can't find a target that matches: {0}. Available pages: {1}", targetUrl, JSON.stringify(targets.map(target => target.url))));
    }
    // If all possible targets appear to be attached to have some other devtool attached, then fail
    const targetsWithWSURLs = filteredTargets.filter(target => !!target.webSocketDebuggerUrl);
    if (!targetsWithWSURLs.length) {
        throw new Error(localize('attach.devToolsAttached', "Can't attach to this target that may have Chrome DevTools attached: {0}", filteredTargets[0].url));
    }
    filteredTargets = targetsWithWSURLs;
    if (filteredTargets.length > 1) {
        vscode_debugadapter_1.logger.log('Warning: Found more than one valid target page. Attaching to the first one. Available pages: ' + JSON.stringify(filteredTargets.map(target => target.url)));
    }
    return filteredTargets[0];
}
function _fixRemoteUrl(remoteAddress, target) {
    if (target.webSocketDebuggerUrl) {
        const wsAddress = target.webSocketDebuggerUrl.split(':')[1];
        const replaceAddress = '//' + remoteAddress;
        if (wsAddress !== replaceAddress) {
            target.webSocketDebuggerUrl = target.webSocketDebuggerUrl.replace(wsAddress, replaceAddress);
        }
        target.webSocketDebuggerUrl = target.webSocketDebuggerUrl.replace('//127.0.0.1', replaceAddress);
        target.webSocketDebuggerUrl = target.webSocketDebuggerUrl.replace('//localhost', replaceAddress);
    }
    return target;
}

//# sourceMappingURL=chromeTargetDiscoveryStrategy.js.map
