const fs = require("fs");
const https = require("https");
const express = require("express");
const socketio = require("socket.io");
const sanitizeHtml = require("sanitize-html");
const basicAuth = require("express-basic-auth");


function getCurrentTime() {

    function addZero(i) {
        if (i < 10) {
            i = "0" + i;
        }
        return i;
        }
        
    var d = new Date();

    var day = addZero(d.getUTCDate());
    var month = addZero(d.getUTCMonth() + 1);
    var year = d.getFullYear();

    var h = addZero(d.getHours());
    var m = addZero(d.getMinutes());
    var s = addZero(d.getSeconds());
    return "[" + day + "-"+ month + "-" + year + " " + h + ":" + m + ":" + s + "]";
    
}

function log(message) {
    console.log(getCurrentTime() + " " + message);
}


const app = express(); //The base http server, use by socketio and https serveur

const https_options = {
    key: fs.readFileSync("./privkey.pem"),
    cert: fs.readFileSync("./fullchain.pem"),
    requestCert: false,
    rejectUnauthorized: false
}

const socketHTTPSServer = https.createServer(https_options, app);
const webHTTPSServer = https.createServer(https_options, app);

const io = socketio(socketHTTPSServer, {
    cors: {
        origin: "https://danby.aniere.fr",
    },
    secure: true
});

usersConnected = 0;
lastUsername = 0;
messagesHistory = []

io.on("connection", (client) => {
        
    client.on("disconnect", () => {
        usersConnected--;
        io.sockets.emit("update-count", {value: usersConnected});

        log(`${client.denisFanNumber} has disconnected`);
    });

    client.on("message", (data) => {
        if(data.message.toLowerCase().includes("denis")) {

            message = sanitizeHtml(data.message, {allowedTags: [], allowedAttributes: {}});

            io.sockets.emit("new-message", {author: client.denisFanNumber, message: message});
            log(`${client.denisFanNumber} : ${message}`);

            messagesHistory.push([client.denisFanNumber, message]);
            if(messagesHistory.length > 20) {
                messagesHistory.shift();
            }

        } else {
            client.emit("warning");
            log(`${client.denisFanNumber} : ${data.message} (INVALID)`);
        }
    });

    lastUsername++;
    usersConnected++;

    io.sockets.emit("update-count", {value: usersConnected});

    client.denisFanNumber = "DenisFan" + lastUsername;
    client.emit("username", {username: "DenisFan" + lastUsername});
    client.emit("previous-messages", {messages: messagesHistory});

    log(`${client.denisFanNumber} is now connected`);    
});  


app.use(express.static("src"));

app.get("/clear", basicAuth({users:{"quentin": "BlanquerCaca89"}, challenge: true}), (req, res) => {
    messagesHistory = [];
    res.send("message history was cleared");
    io.sockets.emit("refresh");
    
    log("Admin cleared messages history");
});

app.listen(80, () => {
    log("Web server started on port 80")
});

webHTTPSServer.listen(443, () => {
    log("Web HTTPS server started on port 443");
});

socketHTTPSServer.listen(3000, () => {
    log("Socket HTTPS server started on port 3000");
});
