const reachability = require("./build/Release/reachability.node");
const EventEmitter = require('events');


const main = new EventEmitter();
const ReachabilityChanged = "ReachabilityChangedEvent";
let hasCallback = false;

const throttle = (cb, limit) => {
    var waiting = false;
    return function () {
        if (!waiting) {
            cb.apply(this, arguments);
            waiting = true;
            setTimeout(function () {
                waiting = false;
            }, limit);
        }
    }
}

const emit = throttle((value) => main.emit(ReachabilityChanged, value), 100);

const change = () => setTimeout(() => {
	if (main.listenerCount(ReachabilityChanged) === 0) {
		hasCallback &&  reachability.setCallback("www.adobe.com", null);
		hasCallback = false;
	} else {
		!hasCallback && reachability.setCallback("www.adobe.com", emit);
		hasCallback = true;
	}
});

Object.defineProperty(main, 'isOnline', {
  configurable: false,
  get: () => {
    return reachability.isOnline();
  }
});


main.on("newListener", change);
main.on("removeListener", change);
main.ReachabilityChanged = ReachabilityChanged;
module.exports = main;
