// Socket IO - Communication

var socketLink = null

fetch('/internal/socketlink', {
    method: "GET"
}).then(link => {socketLink = link})

const socket = io(socketLink);

socket.on("connect", () => {
    console.log("Connecté au serveur par le Socket avec l'ID : " + socket.id)
});

socket.on("disconnect", (log) => {
    window.location.href = "/"
})

function get(request) {

    return new Promise((resolve, reject) => {

        socket.emit("GET/" + request)
        console.log("Envoi de la requête GET : " + request)
        
        socket.once("ANSWER/GET/" + request, (answer) => {
            
            console.log("Réponse pour la requête : " + request)
       
            resolve(answer)
                    
        })
        
    })
    
}

function post(request, value) {

    return new Promise((resolve, reject) => {

        socket.emit("POST/" + request, value)
        console.log("Envoi de la requête POST : " + request)
        
        socket.once("ANSWER/POST/" + request, (answer) => {
            
            console.log("Réponse pour la requête : " + request)
       
            resolve(answer)
                    
        })
        
    })
    
}



function getSocket() {

    return socket
}
