"use strict";

Object.defineProperty(exports, "__esModule", {
    value: !0
});

var ping;

try {
    ping = require("net-ping");
} catch (e) {
    console.error("PingAgent: load net-ping failed:", e);
}

var PingAgent = function() {
    function a(a) {
        var b = this;
        this.targetIp = a, this.running = !1, this.sumTime = 0, this.minTime = 0, this.maxTime = 0, this.okCount = 0, this.errorCount = 0, this.pingCount = 0, console.error("PingAgent:<init>:" + a);
        var c = a.split(".").map(function(a) {
            return parseInt(a);
        }), d = 256 * c[2] + c[3];
        try {
            if (!ping) throw new Error("PingAgent: load net-ping failed");
            if (!isFinite(d)) throw new Error("PingAgent: not a ipv4 address: " + a);
            this.session = ping.createSession({
                sessionId: d,
                timeout: 1e3
            }), this.session.on("error", function(a) {
                return b.error = "" + a;
            });
        } catch (e) {
            this.error = "" + e;
        }
    }
    return a.prototype.start = function() {
        var a = this;
        return this.error ? void setTimeout(function() {
            return a.onResponse(a.error);
        }, 0) : (this.running = !0, void this.send());
    }, a.prototype.stop = function() {
        this.running = !1, this.session && this.session.close();
    }, Object.defineProperty(a.prototype, "isRunning", {
        get: function() {
            return this.running;
        },
        enumerable: !0,
        configurable: !0
    }), a.prototype.onResponse = function(a, b) {}, a.prototype.onUnexpectedError = function(a) {}, a.prototype.send = function() {
        var a = this, b = Date.now();
        this.pingCount++;
        var c = !1;
        this.session.pingHost(this.targetIp, function(d, e, f, g) {
            if (a.running) {
                if (c) return void console.warn(new Date().toLocaleString() + " PingAgent:send:opps! get results twice! addr=" + a.targetIp);
                c = !0;
                var h = Date.now() - b, i = g && f ? g - f : NaN, j = isFinite(i) ? i : h;
                (!isFinite(i) || Math.abs(i - h) > 50) && console.warn(new Date().toLocaleString() + " PingAgent:send:strange result:dt=" + h + ",rt=" + i + ", addr=" + a.targetIp), 
                d ? (a.errorCount++, d instanceof ping.RequestTimedOutError ? a.onResponse("timeout") : d instanceof ping.DestinationUnreachableError ? a.onResponse("unreachable") : a.onResponse(d.toString())) : (a.onResponse(null, j), 
                a.okCount++, a.sumTime += j, a.minTime > j && (a.minTime = j), a.maxTime < j && (a.maxTime = j)), setTimeout(function() {
                    return a.send();
                }, Math.max(0, 2e3 - h));
            }
        });
    }, a;
}();

exports.PingAgent = PingAgent;
//# sourceMappingURL=PingAgent.js.map