const net = require('net');
var server = net.createServer(),
	clientList = [];
const PORT = 65501;
const HOST = '127.0.0.1';

const huya_danmu = require('./hydanmu')
const { LiveWS, LiveTCP, KeepLiveWS, KeepLiveTCP } = require('./bililiveapi')

server.on('connection', function(socket) {
	socket.name = socket.remoteAddress + ':' + socket.remotePort
	console.log(socket.name + '建立连接.')
	clientList.push(socket)
	
	socket.on('data', function(data) {
		var msg = JSON.parse(data)
		//var msg = JSON.stringify(data)
		if (msg.type === 'hy') {
			console.log('虎牙')
			hyconnet(msg.id)
		} else if (msg.type === 'bili') {
			console.log('B站')
			biliconnet(msg.id)
		}
	})
})

function biliconnet (biliroomid) {
	const live = new KeepLiveWS(Number(biliroomid))
	live.on('open', function() {
		clientList[0].write('房间：' + biliroomid + ' 连接成功！')
	})
	live.on('live', () => {
		live.on('heartbeat', function(bilip) {
			clientList[0].write('{"cmd":"bilip","p":"' + bilip.toString() + '"}')
		})
		live.on('DANMU_MSG', function(bilimsg) {
			clientList[0].write(JSON.stringify(bilimsg))
		})
	})
}

function hyconnet (hyroomid) {
	const client = new huya_danmu(hyroomid)
	client.on('connect', () => {
		clientList[0].write(`已连接服务器 ${hyroomid}房间弹幕~`)
	})
	client.on('message', msg => {
		switch (msg.type) {
			case 'chat':
				clientList[0].write(`[${msg.from.name}]:${msg.content}`)
				break
		}
	})
	client.on('error', e => {
	})
	client.start()
}

server.listen(PORT, HOST)
