/*
 * Copyright (C) 2021 Thomas Van Acker
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 *
 * This project is hosted on https://git.bitscuit.be/bitscuit/Fawkes
 *
*/

// Imports
const http = require("http");
const url = require("url");
const fs = require("fs");
const util = require("util");
const crypto = require("crypto");

// Vars
const hostname = "192.168.0.128"; // Enter your local IP address here
const port = 8001; // Enter a port number here

var ids = [];
var sockets = [];


// Create HTTP server
const server = http.createServer((req, res) => {
	// Parse url
	const requrl = url.parse(req.url);
	var reqpath = requrl.pathname;
	if(reqpath == "/") reqpath = "/index.html";

	// Respond to requests
	try{
		// Return requested page
		res.statusCode = 200;
		res.write(fs.readFileSync("html"+reqpath));
		res.end();

	}catch(error){
		// 404 if page not found
		res.statusCode = 404;
		res.setHeader("Content-Type", "text/plain");
		res.end("404 - Page Not Found");
	}
});


// Create socket.io server
const io = require("socket.io")(server); // Can only be done when server is created

io.on("connection", (socket) => {
	console.log("New user connected!");

	// Give user unique ID
	sockets.push(socket);
	var userId = sha256("USER"+rand(0,9999999)+"TIME"+Date.now()).substr(0, 10);
	ids.push(userId);
	console.log("userId = "+userId);
	
	// Init socket listeners
	
	// Disconnect
	socket.on("disconnect", () => {
		console.log("User "+userId+" disconnected!");

		// Remove from user lists
		var index = sockets.indexOf(socket);
		if(index != -1){
			// When in users list
			ids.splice(index, 1);
			sockets.splice(index, 1);
		}
	});


});


// Start HTTP server
server.listen(port, hostname, () => {
	console.log("Server running at http://"+hostname+":"+port);
});




// Helper methods
function rand(min, max){
	return Math.floor(Math.random()*(max-min) + min);
}
function sha256(message){
	return crypto.createHash("sha256").update(message).digest("hex");
}




























