const dgram = require('dgram')
const message =  new Buffer(JSON.stringify({action:'getInfo'}))
const timeout = 10 * 1000 //10 seconds
const detectInterval = 3* 1000 
let currentCard = null
let activeTime = 0
const detectedMap ={}

exports.getStarterUrl = () => {
	//return 'http://localhost:808/test.html'
	if(!currentCard){
		return 'test.html'
	}
	return `http://${currentCard.ip}:${currentCard.starterPort}/?fromDetector=true`
}
let detectedMapCallback = null
exports.setCallback = function(cb){
	detectedMapCallback = cb
	detectedMapCallback(detectedMap)
}

//检查超时并删除
setInterval(checkTimeout,1000)
setInterval(checkTimeout2,1000)
//对所有网卡定时广播
broadcastToAll()

function broadcastToAll(){
	let ips = getIps()
	ips.forEach(function(ip){
		broadcast(ip)
	})
}

function broadcast(ip){

	var socket = dgram.createSocket('udp4')

	var sendUdp =function(){
		socket.send(message, 0, message.length, 22222, '255.255.255.255', (err,b) => {
		});
	}
	var interval
	socket.on('message', (msg, rinfo) => {
		//alert(`socket got: ${msg} from ${rinfo.address}:${rinfo.port}`);
		  try{
			  var data = JSON.parse(msg)
			  data.ip = rinfo.address
			  //notify ip 2017-2-9
			  //var msg =  Buffer.from(JSON.stringify({action:'notifyIp',detectedIp: rinfo.address}))
			  //socket.send(msg, 0, msg.length, 22222, rinfo.address, (err,b) => {});
			  /////////////////////
			  onGetDevice(data)
		  }catch(e){}
	});
	socket.on('error', (err) => {
	  console.log(`socket error:\n${err.stack}`);
	  clearInterval(interval)
	  broadcast(ip)
	  socket.close();
	});
	socket.on('listening', () => {
	  var address = socket.address();
	  //alert(`socket listening ${address.address}:${address.port}`);
	});


	socket.bind(null, ip, function () {

		socket.setBroadcast(true);
		interval = setInterval(sendUdp, detectInterval)
		sendUdp()
	});


}

function checkTimeout(){
	if(Date.now() - activeTime >timeout){		
		currentCard = null		
	}			
}
function checkTimeout2(){
	var timeoutDevices =[]
	for(var id in detectedMap){
		if(Date.now() - detectedMap[id].lastActive >timeout){		
			timeoutDevices.push(id)
		}			
	}
	timeoutDevices.forEach(function(id){
		delete detectedMap[id]
	})
}

function getIps(){
	var result = []
	var os = require('os')
	var its = os.networkInterfaces()
	for(var i in its){
		var arr = its[i]
		for(var j in arr){
			var info = arr[j]
			if(info && info.family.toLowerCase() =='ipv4' && info.address != '127.0.0.1')
				result.push(info.address)
		}
	}
	return result
}

function onGetDevice(data) {
	//alert(data.ip)
	if(!currentCard || currentCard.version < data.version){
		//alert(JSON.stringify(data))
		currentCard = data
	}
	if(currentCard.id == data.id){
		activeTime = Date.now()
	}
	data.lastActive = Date.now()
	detectedMap[data.id] = data
	if(detectedMapCallback)
		detectedMapCallback(detectedMap)
}
