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) => {
			logger.wslog("api received:", message);
			await api.exec(peerAddress, message, (rs, encryptor) => {
				logger.wslog("api sended:", rs);
				let result = JSON.stringify(rs);
				if (encryptor)
					throw new Error("encryptor is deprecated. Use TLS wrapping");
				ws.send(result);
			});
		});
	});
	
	logger.log(`WebSocket API successful runned at port ${port}`);
}
