"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PingPongWs = void 0;
const utils_1 = require("@streamr/utils");
const logger = new utils_1.Logger(module);
class PingPongWs {
    constructor(getConnections, pingIntervalInMs) {
        this.getConnections = getConnections;
        this.pingInterval = setInterval(() => this.pingConnections(), pingIntervalInMs);
    }
    getRtts() {
        const rtts = {};
        this.getConnections().forEach((connection) => {
            const rtt = connection.getRtt();
            if (rtt !== undefined) {
                rtts[connection.getPeerId()] = rtt;
            }
        });
        return rtts;
    }
    stop() {
        clearInterval(this.pingInterval);
    }
    pingConnections() {
        this.getConnections().forEach((connection) => {
            if (!connection.getRespondedPong()) {
                logger.warn(`terminate connection to %s because didn't receive pong`, connection.getPeerId());
                connection.terminate();
            }
            else {
                try {
                    connection.ping();
                    logger.trace('pinging %s (current rtt %s)', connection.getPeerId(), connection.getRtt());
                }
                catch (e) {
                    logger.warn(`terminating connection because error thrown when attempting to ping %s: %s`, connection.getPeerId(), e);
                    connection.terminate();
                }
            }
        });
    }
}
exports.PingPongWs = PingPongWs;
//# sourceMappingURL=PingPongWs.js.map