const https = require('https');
const WebSocket = require('ws');
const logger = require("./logger");

module.exports = (address, port, api) => {
	// console.log(global.openSSH);
	// console.log(global.openSSH.cert.toString("utf-8"));
	
	const wss = new WebSocket.Server({ address, port });

	wss.on('connection', function connection(ws, req) {
		const peerAddress = `${req.socket.remoteAddress}:${req.socket.remotePort}`;
		console.log("peerAddress is", peerAddress);
		ws.on('message', async (message) => {
			//console.log('received: %s', message);
			logger.wslog("api received:", message);
			try {
				message = Buffer.from(message, "base64");
			} catch (_) {}
			await api.exec(peerAddress, message, (rs, encryptor) => {
				logger.wslog("api sended:", rs);
				let result = JSON.stringify(rs);
				if (encryptor)
					result = encryptor.encrypt(result).toString('base64');
				ws.send(result);
			});
		});
	});
	
	logger.log(`WebSocket API successful runned at port ${port}`);
}
