'use strict';

const https = require('https')
const WebSocket = require('ws')
const WebSocketServer = require('wss')
const fs = require('fs')

const serverConfig = {
	key: fs.readFileSync('key.pem'),
	cert:  fs.readFileSync('cert.pem')
}

const httpServer = https.createServer(serverConfig, (req, res) => {
	res.writeHead(200)
	res.end()
})

httpServer.listen(3535, '0.0.0.0')

// Now for the websockets server

const wss = new WebSocketServer({server: httpServer})

wss.on('connection', function(socket) {
	socket.on('message', function(message) {
		console.log('Socket received message: ', message)
		wss.broadcast(message)
	})
})

wss.broadcast = function(data) {
	console.log('Cuurent clients list: ', this.clients)
	this.clients.forEach(client => {
		if(client.readyState == WebSocket.OPEN) {
			client.send(data)
		}
	})
}

console.log('serving on https://localhost:3535')