var util = require('util');
var EventEmitter = require('events').EventEmitter;
var exec = require('child_process').exec;


var IpPoll = function(target) {
    var self = this;

    var regexp = /([0-9]+)% packet loss/m;
    var command = "LANG=C ping -c 2";

    this.pollState = function() {
        try {
            exec(command + " " + target, function (error, stdout, stderr) {
                // console.log(stdout);

                var matches = regexp.exec(stdout);
                if (matches != null) {

                    // console.log("matches " + JSON.stringify(matches));
                    // console.log("length: " + matches.length);
                    // console.log("matches 1: " + matches[1]);

                    if (matches.length === 2) {
                        self.emit('doneState', matches[1] === "0");
                    }
                }
            });
        } catch(err) {
            self.emit('doneState', "unknown");
        }
    };

};

util.inherits(IpPoll, EventEmitter);
module.exports = IpPoll;
