/*---------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*/
"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());
    });
};
const utils = require("../utils");
const chromeUtils = require("./chromeUtils");
const nls = require("vscode-nls");
const localize = nls.config(process.env.VSCODE_NLS_CONFIG)(__filename);
class ChromeTargetDiscovery {
    constructor(_logger, _telemetry) {
        this.logger = _logger;
        this.telemetry = _telemetry;
    }
    getTarget(address, port, targetFilter, targetUrl) {
        return __awaiter(this, void 0, void 0, function* () {
            const targets = yield this.getAllTargets(address, port, targetFilter, targetUrl);
            if (targets.length > 1) {
                this.logger.log('Warning: Found more than one valid target page. Attaching to the first one. Available pages: ' + JSON.stringify(targets.map(target => target.url)));
            }
            const selectedTarget = targets[0];
            this.logger.verbose(`Attaching to target: ${JSON.stringify(selectedTarget)}`);
            this.logger.verbose(`WebSocket Url: ${selectedTarget.webSocketDebuggerUrl}`);
            return selectedTarget.webSocketDebuggerUrl;
        });
    }
    getAllTargets(address, port, targetFilter, targetUrl) {
        return __awaiter(this, void 0, void 0, function* () {
            const targets = yield this._getTargets(address, port);
            this.telemetry.reportEvent('targetCount', { numTargets: targets.length });
            if (!targets.length) {
                return utils.errP(localize(0, null));
            }
            return this._getMatchingTargets(targets, targetFilter, targetUrl);
        });
    }
    ;
    _getTargets(address, port) {
        const url = `http://${address}:${port}/json`;
        this.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 => this._fixRemoteUrl(address, port, target));
                }
            }
            catch (e) {
            }
            return utils.errP(localize(1, null, jsonResponse));
        }, e => {
            return utils.errP(localize(2, null, e.message));
        });
    }
    _getMatchingTargets(targets, targetFilter, targetUrl) {
        if (targetFilter) {
            // Apply the consumer-specific target filter
            targets = targets.filter(targetFilter);
        }
        // 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(3, null, 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(4, null, filteredTargets[0].url));
        }
        return targetsWithWSURLs;
    }
    _fixRemoteUrl(remoteAddress, remotePort, target) {
        if (target.webSocketDebuggerUrl) {
            const addressMatch = target.webSocketDebuggerUrl.match(/ws:\/\/(.*:\d+)\/?/);
            if (addressMatch) {
                const replaceAddress = `${remoteAddress}:${remotePort}`;
                target.webSocketDebuggerUrl = target.webSocketDebuggerUrl.replace(addressMatch[1], replaceAddress);
            }
        }
        return target;
    }
}
exports.ChromeTargetDiscovery = ChromeTargetDiscovery;

//# sourceMappingURL=chromeTargetDiscoveryStrategy.js.map
