<div class="users">
    <h1>Gestionnaire des utilisateurs</h1> 
</br>
<div class="homepanel">
    <div class="row w-100">
        <div class="hbox col">
             <h1><i class="fa fa-users"></i> Utilisateurs</h1>
             <div id="gus_panel" class="gus_users">
               
             </div>
            <button id="gus_add" class="gus_add"><i class="fa fa-plus"></i> Ajouter un utilisateur</button>
            <div id="gus_info"></div>
         </div>

        
    </div>

    </div>
</div>
<dialog class="gus_adduser" id="gus_adduser">
    <h1><i class="fa fa-plus"></i> Ajouter un utilisateur</h1>
        <div class="gus_add_imagediv">
            <img width="200" height="200" id="gus_add_image" class="gus_add_image" src="/images/standalone.png">
            <br>
            <input class="gus_image_upload" accept="image/png, image/jpeg" name="apic" type="file" id="gus_image_upload"/>
            <br>
            <div style="color: rgb(255, 76, 76);" id="gus_add_image_info"></div>
        </div>
    <div class="form">
        <p>Nom d'utilisateur</p>
        <input class="inp" id="gus_add_username" type="text">
        <p>Nom complet :</p>
        <input class="inp" id="gus_add_fullname" type="text">
        <p>Mot de passe :</p>
        <input class="inp" id="gus_add_password" type="password">
        <p>Niveau de permission :</p>
        <select class="inp" id="gus_add_perm">
            <option>Niveau 1 : (Utilisateur)</option>
            <option>Niveau 2 : (Editeur)</option>
            <option>Niveau 3 : (Operateur)</option>
            <option>Niveau 4 : (Administrateur)</option>
        </select>
        <div style="color: rgb(255, 76, 76);" id="gus_add_info"></div>
    </div>
    <button onclick="getPage('users.html')" id="gus_add_close" class="gus_add_close">Annuler</button>
    <button id="gus_add_confirm" class="gus_add_confirm">Ajouter</button>
    


</dialog>


<div id="gus_dialoguser">

</div>



<script>

    if(typeof adduserform  == 'undefined'){

        const panel = document.getElementById("gus_panel")
        const dialogUserall  = document.getElementById("gus_dialoguser")

        showUsers()

        /* EXAMPLE OF A LINE

         <div class="gus_line row w-100">
                    <div class="col-lg">
                        <p><img width="200" class="gus_image" src="images/userspics/' + user + '.png"> <span id="' + user + "_fullname" + '"></span></p>
                    </div>
                    <div class="col-lg">
                        <p>Dernière connexion : <span id="' + user + "_lastco" + '"></span></p>
                    </div>
                    <div class="col-lg">
                        <p>Niveau de permissions : <span id="' + user + "_permLevel" + '"></span></p>
                    </div>
                    <div class="col-lg">
                    <button id="' + user + "_edit" + '" class="gus_edit"><i class="fa fa-pen"></i></button>
                    <button id="' + user + "_deco" + '" class="gus_signout"><i class="fa-solid fa-arrow-right-from-bracket"></i></button>
                    <button id="' + user + "_del" + '" class="gus_delete"><i class="fa fa-trash"></i></button>
                </div>
        </div>

        */

        function showUsers() {

            var number = Date.now()

            

            var dialogtoshow = new Array()
            var usertoshow = new Array()

            fetch('/usermanager', {
                method: 'POST',
                redirect: 'follow',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({"request":"get", "value": ""})
            })
            .then(response => response.json())
            .then(response => load(response))

            
                        
            function load(response) {

                if(response.result == "failed") {
                    content.innerHTML = ' <h1 style="color:red;"><i style="color:yellow; font-size: 2vw;" class="fa fa-warning"></i>  Erreur de chargement des données - Erreur : ' + response.content  + '</h1>'
                    console.log("FAILED")
                        
                } else if(response.result == "success") {

                    var fullname;
                    var lastco;
                    var permLevel;

                    for(var user of response.content) {

                       
                        usertoshow.push('<div class="gus_line row w-100"><div class="col-lg"><p><img width="200" class="gus_image" src="images/userspics/'+ user +'.png?' + number + '"> <span id="' + user + "_fullname"+'"></span></p></div><div class="col-lg"><p>Dernière connexion : <span id="' + user + "_lastco"+'"></span></p></div><div class="col-lg"><p>Niveau de permissions : <span id="'+user+"_permLevel"+'"></span></p></div><div class="col-lg"><button id="'+user+"_edit"+'" class="gus_edit"><i class="fa fa-pen"></i></button><button id="'+user+"_deco"+'" class="gus_signout"><i class="fa-solid fa-arrow-right-from-bracket"></i></button><button id="'+user+"_del"+'" class="gus_delete"><i class="fa fa-trash"></i></button></div></div>')
                        dialogtoshow.push('<dialog class="gus_adduser" id="' + user + '_editDialog"> <h1><i class="fa fa-pen"></i> Editer un utilisateur</h1> <div class="gus_add_imagediv"> <img width="200" height="200" id="gus_add_image" class="gus_add_image" src="/images/userspics/' + user + '.png?' + number + '"> <br> <input class="gus_image_upload" accept="image/png, image/jpeg" name="apic" type="file" id="' + user + '_image_upload"/> <br> <div style="color: rgb(255, 76, 76);" id="' + user + '_add_image_info"></div> </div> <div class="form"> <p>Nom d\'utilisateur</p> <input class="inp" id="' + user + '_add_username" type="text"> <p>Nom complet :</p> <input class="inp" id="' + user + '_add_fullname" type="text"> <p>Mot de passe :</p> <input class="inp" id="' + user + '_add_password" type="password"> <p>Niveau de permission :</p> <select class="inp" id="' + user + '_add_perm"> <option>Niveau 1 : (Utilisateur)</option> <option>Niveau 2 : (Editeur)</option> <option>Niveau 3 : (Operateur)</option> <option>Niveau 4 : (Administrateur)</option> </select> <div style="color: rgb(255, 76, 76);" id="' + user + '_add_info"></div> </div> <button onclick="getPage(\'users.html\')" id="' + user + '_add_close" class="gus_add_close">Annuler</button> <button id="' + user + '_add_confirm" class="gus_add_confirm">Editer</button> </dialog> ')

                        panel.innerHTML = usertoshow.join("")
                        dialogUserall.innerHTML = dialogtoshow.join("")


                        fetch('/get', {
                            method: 'POST',
                            redirect: 'follow',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({"request":"all", "name": user, "additional": ""})
                        })
                        .then(response => response.json())
                        .then(response => after(response))


                        function after(response) {

                            

                            const date = new Date(response.content.lastconnexion)

                            var gmonth = date.getMonth()
                            var gday = date.getDate()
                            var gHour = date.getHours()
                            var gMinute = date.getMinutes()
                            var gSecondes = date.getSeconds()


                            if(date.getMonth() + 1 <= 9) {
                                gmonth = "0" + (date.getMonth() + 1)
                            }

                            if(date.getDate() + 1 <= 9) {
                                gday = "0" + date.getDate()
                            }

                            if(date.getHours() + 1 <= 9) {
                                gHour = "0" + date.getHours()
                            }

                            if(date.getMinutes() + 1 <= 9) {
                                gMinute = "0" + date.getMinutes()
                            }

                            if(date.getSeconds() + 1 <= 9) {
                                gSecondes = "0" + date.getSeconds()
                            }

                            var currentDate = gday + "-" + gmonth + "-" + date.getFullYear()  + " - " + gHour + ":" + gMinute



                            fullname = document.getElementById(response.content.username + "_fullname")
                            lastco = document.getElementById(response.content.username + "_lastco")
                            permLevel = document.getElementById(response.content.username + "_permLevel")

                            fullname.innerHTML = response.content.fullname
                            permLevel.innerHTML = response.content.permLevel
                            lastco.innerHTML = currentDate;

                            const editBtn = document.getElementById(response.content.username + "_edit")
                            const decoBtn = document.getElementById(response.content.username +"_deco")
                            const delBtn = document.getElementById(response.content.username + "_del")

                            delBtn.addEventListener("click", () => {

                                fetch('/usermanager', {
                                    method: 'POST',
                                    redirect: 'follow',
                                    headers: {
                                        'Accept': 'application/json',
                                        'Content-Type': 'application/json'
                                    },
                                    body: JSON.stringify({"request":"del", "value": response.content.username})
                                })


                                getPage("users.html")

                            })

                            decoBtn.addEventListener("click", () => {

                                fetch('/usermanager', {
                                    method: 'POST',
                                    redirect: 'follow',
                                    headers: {
                                        'Accept': 'application/json',
                                        'Content-Type': 'application/json'
                                    },
                                    body: JSON.stringify({"request":"deco", "value": response.content.username})
                                })

                                gusInfo.innerHTML = "<p style='color: rgb(130, 255, 163); padding: 1vw;'>Le Token de l'utilisateur <strong>" + response.content.username + "</strong> a été supprimé</p>"
                                

                            })

                            editBtn.addEventListener("click", () => {

                                const editDialog = document.getElementById(response.content.username + "_editDialog")  

                                const edituserUsername = document.getElementById(response.content.username + "_add_username")
                                const edituserPassword = document.getElementById(response.content.username + "_add_password")
                                const edituserFullname = document.getElementById(response.content.username + "_add_fullname")
                                const edituserPerm = document.getElementById(response.content.username + "_add_perm")
                                const edituserInfo = document.getElementById(response.content.username + "_add_info")
                                const edituserImage = document.getElementById(response.content.username + "_image_upload")

                                const edituserConfirm = document.getElementById(response.content.username + "_add_confirm")

                                edituserUsername.value = response.content.username;
                                edituserFullname.value = response.content.fullname;

                          
                                
                                if(response.content.permLevel == 1) {

                                    edituserPerm.value = "Niveau 1 : (Utilisateur)";
                                } else if(response.content.permLevel == 2) {

                                    edituserPerm.value = "Niveau 2 : (Editeur)";
                                } else if(response.content.permLevel == 3) {

                                    edituserPerm.value = "Niveau 3 : (Operateur)";
                                } else if(response.content.permLevel == 4) {

                                    edituserPerm.value = "Niveau 4 : (Administrateur)";
                                }

                                edituserConfirm.addEventListener("click", () => {

                                    edituserInfo.innerHTML = ""



                                    if(edituserUsername.value != "" && edituserFullname.value != "") {

                                        var level = 1;

                                        if(edituserPerm.value == 'Niveau 1 : (Utilisateur)') {
                                                level = 1

                                        } else if(edituserPerm.value == 'Niveau 2 : (Editeur)') {
                                                level = 2

                                        } else if(edituserPerm.value == 'Niveau 3 : (Operateur)') {
                                                level = 3

                                        } else if(edituserPerm.value == 'Niveau 4 : (Administrateur)') {
                                                level = 4

                                        } 
                                    

                                        const requestData = {
                                            "original":response.content.username,
                                            "username":edituserUsername.value,
                                            "fullname":edituserFullname.value,
                                            "permLevel": level,
                                            "password": edituserPassword.value

                                        }

                                        

                                        fetch('/usermanager', {
                                            method: 'POST',
                                            redirect: 'follow',
                                            headers: {
                                                'Accept': 'application/json',
                                                'Content-Type': 'application/json'
                                            },
                                            body: JSON.stringify({"request":"edit", "value": requestData})
                                        })
                                        .then(response => response.json())
                                        .then(response => editresp(response))


                                        function editresp(eresponse) {
                                            if(eresponse.result == "failed") {
                                                content.innerHTML = ' <h1 style="color:red;"><i style="color:yellow; font-size: 2vw;" class="fa fa-warning"></i>  Erreur de chargement des données - Erreur : ' + eresponse.content  + '</h1>'
                                                console.log("FAILED")
                                                    
                                            } else if(eresponse.result == "success") {

                                                if(eresponse.content != "DATA_VALID") {
                                                    edituserInfo.innerHTML = "L'édition de l'utilisateur a échoué."

                                                } else {

                                                    if(edituserImage.files[0] != null) {
                                            
                                            
                                                        const image_acc = new FormData();
                                                        image_acc.append("apic", edituserImage.files[0])
                                                            
                                                        fetch('/upload', {
                                                                method: 'POST',
                                                                mode:"cors",
                                                                cache:"no-cache",
                                                                credentials:"same-origin",
                                                                headers: {
                                                                    "uploadforuser": requestData.username

                                                                },
                                                                referrerPolicy:"no-referrer",
                                                                redirect: 'follow',
                                                                body: image_acc
                                                        }).then(response => getPage("users.html"))
                                                    
                                                    
                                                    } else {
                                                        getPage("users.html")

                                                    }

                                                   

                                                }
                                                


                                            }


                                        }

                                        


                                    } else {
                                        edituserInfo.innerHTML = "<p>L'utilisateur ne peut pas ne pas avoir de nom d'utilisateur et de nom complet</p>"

                                    }
                                })

                                
                                
                                editDialog.showModal()

                            })


                            

                            
                        }


                    }   



                }

            }
            
            
           

        }

        const imgInput = document.getElementById("gus_image_upload")
        const imgEl = document.getElementById("gus_add_image")
        const imgInfo = document.getElementById("gus_add_image_info")

        imgInput.addEventListener("change", (event) => {

            imgInfo.innerHTML = ""
            const nowImage = event.target.files
            const nowImageLength = event.target.files

            if(nowImage[0].type == "image/jpeg" | nowImage[0].type == "image/png") {
                const imageSrc = URL.createObjectURL(nowImage[0]);
                imgEl.src = imageSrc;

            } else {
                imgInput.value = ""
                imgInfo.innerHTML = '<p>Seul les images (JPEG et PNG) sont acceptés.</p>'
            }
            


         })
        
       

        const adduserForm = document.getElementById("gus_adduser")
        const adduserBtn = document.getElementById("gus_add")
        const adduserConfirm = document.getElementById("gus_add_confirm")

        const adduserUsername = document.getElementById("gus_add_username")
        const adduserPassword = document.getElementById("gus_add_password")
        const adduserFullname = document.getElementById("gus_add_fullname")
        const adduserPerm = document.getElementById("gus_add_perm")
        const addInfo = document.getElementById("gus_add_info")
        const gusInfo = document.getElementById("gus_info")
          
            adduserBtn.addEventListener("click", () => { 

                adduserUsername.value = ""
                adduserPassword.value = ""
                adduserFullname.value = ""
                adduserPerm.value = "Niveau 1 : (Utilisateur)"
                addInfo.value = ""
                gusInfo.innerHTML = ""
                imgEl.src = "/images/standalone.png"  ;

                adduserForm.showModal()
            })

            adduserConfirm.addEventListener("click", () => {

                addInfo.innerHTML = ""
                imgInfo.innerHTML = ""

                if(adduserUsername.value != "" && adduserPassword.value != "" && adduserFullname.value != "") {
                    
                    const addUserData = {"username":adduserUsername.value, "password":adduserPassword.value, "fullname":adduserFullname.value, "permLevel":adduserPerm.value }

                    const addUserImage = document.getElementById("gus_image_upload")

                    
                    
                    fetch('/usermanager', {
                        method: 'POST',
                        redirect: 'follow',
                        headers: {
                        'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({"request":"add", "value": addUserData})
                    })
                    .then(response => response.json())
                    .then(response => load(response))
                        
                    function load(response) {
                        if(response.result == "failed") {
                                content.innerHTML = ' <h1 style="color:red;"><i style="color:yellow; font-size: 2vw;" class="fa fa-warning"></i>  Erreur de chargement des données - Erreur : ' + response.content  + '</h1>'
                                console.log("FAILED")
                        
                        } else if(response.result == "success") {
                            
                            if(response.content == "VALID") {
                              
                                if(addUserImage.files[0] != null) {
                                    
                                    
                                    const image_acc = new FormData();
                                    image_acc.append("apic", addUserImage.files[0])
                                        
                                    fetch('/upload', {
                                            method: 'POST',
                                            mode:"cors",
                                            cache:"no-cache",
                                            credentials:"same-origin",
                                            headers: {
                                                "uploadforuser": adduserUsername.value

                                            },
                                            referrerPolicy:"no-referrer",
                                            redirect: 'follow',
                                            body: image_acc
                                    })
                                
                                
                                }  

                                gusInfo.innerHTML = "<p style='color:rgb(130, 255, 163); padding: 1vw;'>Ajout de l'utilisateur <strong>" + adduserUsername.value + "</strong> avec succès.</p>"
                                adduserForm.close()
                                getPage("users.html")

                              
                            } else {
                                addInfo.innerHTML = '<p>' + response.content + '</p>'
                            }
                                    
                           

                             
                        }
                    }

                } else {

                    addInfo.innerHTML = '<p">Tous les champs doivent être remplis</p>'
                }

                

            })
        

        

    }

    
    
</script>

<!-- Style-->
<style>

.gus_adduser p  {
 
    margin-top: 0.5vw;

}

.gus_add_imagediv {

    text-align: center;
    justify-items: center;

   
}

.inp {

    border-style: hidden;
    border-radius: 1vw;
    padding: 0.2vw;
    padding-left: 1vw;
    transition: all 0.2s ease 0s;
    

}

.gus_adduser .gus_image_upload {

    margin-top: 1vw;
    margin-bottom: 1vw;
}


select.inp {

    margin-bottom: 0.5vw;

}

.inp:hover {

    box-shadow: 2px 2px 5px rgba(255, 255, 255, 0.477) ;

}


.inp:focus {

    box-shadow: 5px 5px 5px rgba(0, 174, 255, 0.477) ;

}

.gus_adduser {

    border-radius: 1vw;
    border-color: transparent;
    background-color: rgb(80, 80, 80);
    color: white;
    text-align: center;
    
}

.gus_add_image {

    border-radius: 100%;
}

.gus_add_close {

    border-radius: 1vw;
    border-color: rgb(255, 48, 48);
    border-width: 1%;
    border-style: solid;
    color: white;
    background-color: transparent;
    transition: all 0.2s ease 0s;
    margin: 0.5vw;
    padding: 0.5vw;
    font-size: 1vw;
}

.gus_add_close:hover {
    box-shadow: 1px 1px 10px rgb(255, 48, 48);
    background-color: rgb(255, 48, 48);
    color: black;
}

.gus_add_close:active {
    box-shadow: none;

}

.gus_add_confirm {

    border-radius: 1vw;
    border-color: rgb(0, 174, 255);
    border-width: 1%;
    border-style: solid;
    color: white;
    background-color: transparent;
    transition: all 0.2s ease 0s;
    margin: 0.5vw;
    padding: 0.5vw;
    font-size: 1vw;

}

.gus_add_confirm:hover {
    box-shadow: 1px 1px 10px rgb(0, 174, 255);
    background-color: rgb(0, 174, 255);
    color: black;
}

.gus_add_confirm:active {
    box-shadow: none;

}


.hbox h1 {

    font-size: large;

}

table  {
    color: white;
    
}

.gus_line {

    margin: 1vw;
    text-align: center;
    display: flex;
    vertical-align: middle;
    align-items: center;
}

.gus_image {

   width: 10%;
   border-radius: 100%;
}

.gus_users {

    margin: 1%;
    padding: 1%;
    background-color: rgb(80, 80, 80);
    border-radius: 1vw;
    box-shadow: 5px 5px 5px rgba(80, 80, 80, 0.477) ;
}

.gus_edit {

    border-radius: 100%;
    border-color: rgb(0, 174, 255);
    border-width: 1%;
    border-style: solid;
    color: white;
    background-color: transparent;
    transition: all 0.2s ease 0s;
    width: 2.5vw;
    height: 2.5vw;
    margin-left: 0.5vw;
    margin-right: 0.5vw;
    font-size: 1vw;
    
}

.gus_edit:hover {
    box-shadow: 1px 1px 10px rgb(0, 174, 255);
    background-color: rgb(0, 174, 255);
    color: black;
}

.gus_edit:active {
    box-shadow: none;
    
}

.gus_signout {

    border-radius: 100%;
    border-color: rgb(254, 254, 74);
    border-width: 1%;
    border-style: solid;
    color: white;
    background-color: transparent;
    transition: all 0.2s ease 0s;
    width: 2.5vw;
    height: 2.5vw;
    margin-left: 0.5vw;
    margin-right: 0.5vw;
    font-size: 1vw;
}

.gus_signout:hover {
    box-shadow: 1px 1px 10px rgb(254, 254, 74);
    background-color: rgb(254, 254, 74);
    color: black;
}

.gus_signout:active {
    box-shadow: none;

}

.gus_delete {

    border-radius: 100%;
    border-color: rgb(255, 48, 48);
    border-width: 1%;
    border-style: solid;
    color: white;
    background-color: transparent;
    transition: all 0.2s ease 0s;
    width: 2.5vw;
    height: 2.5vw;
    margin-left: 0.5vw;
    margin-right: 0.5vw;
    font-size: 1vw;
}

.gus_delete:hover {
    box-shadow: 1px 1px 10px rgb(255, 48, 48);
    background-color: rgb(255, 48, 48);
    color: black;
}

.gus_delete:active {
    box-shadow: none;

}

.gus_add {

    border-radius: 1vw;
    border-color: rgb(0, 174, 255);
    border-width: 1%;
    border-style: solid;
    color: white;
    background-color: transparent;
    transition: all 0.2s ease 0s;
    padding: 0.5vw;
    
}

.gus_add:hover {
    box-shadow: 1px 1px 10px rgb(0, 174, 255);
    background-color: rgb(0, 174, 255);
    color: black;
}

.gus_add:active {
    box-shadow: none;

}




.hbox {
    
    margin: 1%;
    padding: 1%;
    background-color: rgb(80, 80, 80);
    border-radius: 1vw;
    box-shadow: 5px 5px 5px rgba(80, 80, 80, 0.477) ;

  }

</style>