var redis = require("redis");
var snmp = require("net-snmp");	
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var _u = require("underscore");

var redisprefix = "mac:";


var SnmpMac = function(hostname, community) {
	var self = this;
	
	var redisClient = redis.createClient();		
	var session = snmp.createSession(hostname, community, { version: snmp.Version2c } );
	
	var baseoid = "1.3.6.1.2.1.17.7.1.2.2.1.3";
	var regexp = /([0-9]+).([0-9]+).([0-9]+).([0-9]+).([0-9]+).([0-9]+)$/;
	var names = [];
	
	redisClient.on("connect", function () {   
		//redisClient.set(redisprefix + "00:80:a3:91:39:1c","ripe-atlas-probe");
		//redisClient.set(redisprefix + "d4:ca:6d:33:cf:79","routerboard");
		
		console.log("SNMP-MAC: connected to redis");
		self.emit('ready');
	});

    redisClient.on('error', function(err) {
        console.log("redis error: " + err);
    });

	function getMacFromOID(oid, callback) {
		var matches = regexp.exec(oid);
		var mac = "";
       
		if(matches != null) {
			for(var i = 1; i < matches.length; i++) {
				var num = parseInt(matches[i]);
				if(num <= 15) mac += "0";
				mac += num.toString(16) + ":";		
			}
			mac = mac.substr(0, mac.length-1);
		
			callback(mac);
		}
	}
			
	function doneCb(error) {
		if (error)
			console.error(error.toString ());
		
		self.emit('done', _u.uniq(names));
	}
	
	function feedCb(varbinds) {
		for (var i = 0; i < varbinds.length; i++) {
			if (snmp.isVarbindError(varbinds[i])) {
				console.error(snmp.varbindError (varbinds[i]));
			} else {						
				if(varbinds[i].value == "3") {	// only valid arp entries
					getMacFromOID(varbinds[i].oid, function(mac) {
//                        console.log(mac);
						redisClient.get(redisprefix + mac, function(err, reply) {
							if(reply != null) {
								names.push(reply);
							}
						});
					}); 
				}	
			}
		}
	}
	
	this.poll = function() {
		names.length = 0;
		session.subtree(baseoid, 20, feedCb, doneCb);
	};
	
	this.stop = function() {
		redisClient.quit();
	};

    this.add = function (mac, name, callback) {
        redisClient.set(redisprefix + mac, name, function (err) {
            if(typeof callback === "function") callback(err);
        });
    };

    this.delete = function(mac, callback) {
        redisClient.del(redisprefix + mac, function(err) {
            if(typeof callback === "function") callback(err);
        });

    };

};

util.inherits(SnmpMac, EventEmitter);

module.exports = SnmpMac;
