const { LogType } = require("loguix")
const fs = require("fs")
const path = require("path")
const { __glob } = require("./global-variables")
const auth = require("./auth")
const plog = new LogType("Web")
const cook = require("cookie")
const http = require("http")

/**
 * NOTE INTERNE
 * 
 * Changer les pictures de users autre part
 */

/**
 * 
 * @param {http.Server} server 
 */

module.exports.serverIO = function(server) {

    const io = require('socket.io')(server)

    io.on("connection", (socket) => {
        let token = cook.parse(socket.handshake.headers.cookie).token
        const user = auth.getUserByToken(token)

        if(user) {
            plog.log("Connexion au panel par '" + user.username + "' avec le socket : " + socket.id)
            user.setLastLogin(new Date())
            /*
            GET REQUEST
            */ 

            // Get Users
            GetRequest("USERINFO", () => {

                GetAnswer("USERINFO", {username: user.username, display_name: user.display_name ,picture: user.picture, permission: user.permission})
            })

    

            socket.on("disconnect", () => {

                plog.log("Déconnexion au panel par '" + user.username + "' avec le socket : " + socket.id)
            })

            function GetRequest(GQname, GQcallback) {
                socket.on("GET/" + GQname, () => {
    
                    plog.log(user.username + " - Socket : " + socket.id  + " - GET/" + GQname + " - [RECIEVED]") 
                    GQcallback()
                })
        
            }
    
            function GetAnswer(GRname, GRvalue) {
            
                plog.log(user.username + " - Socket : " + socket.id  + " - GET/" + GRname + " - [ANSWERED]") 
                socket.emit("ANSWER/GET/" + GRname, GRvalue)
    
            }

        } else {

            socket.disconnect()
            plog.warn("Connexion directe vers le panel avec un token inexistant : " + this.token)
        }
        

        
    
       
    })


}
