<style>
    #users_section{
        width: 80vw;
        margin: auto;
    }
    .pass_blur{
        color:transparent; 
        text-shadow:0 0 20px #555, 0 0 20px #000; 
        border:0; 
        padding:0; 
        margin:0; 
        filter:blur(5px); 
    }
    #users_section li{
        display: flex;
        justify-content: space-between;
        text-align: center;
        margin: 0px auto;
        padding: 10px;
        /* background-color:white; */
    }
    #users_section li div:not(#first_user div){
        /* margin: auto; */
        width: 100px;
        text-align: center;
    }
    #first_user div{
        /* text-align: center; */
        width: 200px;
        text-align: center;
    }
    #users_section ul{
        padding: 0px;
        margin: 0px;
        list-style: none;
        height: 320px;
    }
    #find_user_btns{
        /* display: flex; */
        margin: auto 0px;
        /* height: 25px; */
    }
    .user_edit{
        cursor: pointer;
    }
    
</style>

<div style="display: flex;justify-content: space-between;">
    <h1>пользователи</h1>
    <div id="find_user_btns">
        <button onclick="load_users_data(users_from,true);" class="btn_blue">Найти по имени</button>
        <button onclick="users_from=0;load_interval=5;load_users_data(users_from)" class="btn_blue">Очистить</button>
    </div>
</div>
<section id="users_section">
    <div style="height: 330px;background-color: white;margin-bottom: 3vh;">
        <li id="first_user"><div>Логин</div><div>Пароль</div><div>Админ. права</div><div>Амин. польз</div><div>Админ. объект.</div><div>Удалить</div></li>
        <ul id="user_list" style="padding-inline: 2vw;"></ul>
    </div>
    <div style="display: flex;justify-content: space-between;margin: auto;">
        <div style="display: flex;"><h1>Всего:&nbsp;</h1> <h1 id="users_count">0</h1></div>
        <div style="display: flex;margin: auto 0px;">с&nbsp;<div id="users_from">0</div>&nbsp;по&nbsp;<div id="users_to">10</div></div>
        <div style="margin: auto 0px;"><button id="back_btn" class="btn_gray">< 10 назад</button></div>
        <div style="margin: auto 0px;"><button  id="forw_btn" class="btn_gray">даллее ></button></div>
    </div>
</section>


<script>
    let users_from = 0;
    let load_interval = 5;
    function user_count_check(){
        if(parseInt(document.getElementById("users_count").innerText) >= parseInt(document.getElementById("users_to").innerText)){
            document.getElementById("forw_btn").classList = "btn_blue";
            document.getElementById("forw_btn").setAttribute("onclick",`users_from+=load_interval;load_users_data(users_from);`);

        }
        else{
            document.getElementById("forw_btn").setAttribute("onclick",``);
            document.getElementById("forw_btn").classList = "btn_gray";
        }

        if(parseInt(document.getElementById("users_from").innerText) == 0){
            document.getElementById("back_btn").setAttribute("onclick",``);
            document.getElementById("back_btn").classList = "btn_gray";
        }
        else{
            document.getElementById("back_btn").setAttribute("onclick",`if(users_from-load_interval>=0){users_from-=load_interval;load_users_data(users_from);};`);
            document.getElementById("back_btn").classList = "btn_blue";
        }
    }
    load_users_data(users_from);
    function load_users_data(from,by_name=false){
        // if(to == "forward") {users_from+=load_interval;}
        // else if(to == "back") {users_from-=load_interval;}
        document.getElementById("back_btn").setAttribute("onclick",``);
        document.getElementById("forw_btn").setAttribute("onclick",``);
        document.getElementById("user_list").innerHTML = "";
        document.getElementById("users_from").innerText = from;
        document.getElementById("users_to").innerText = from+load_interval;
        if(!by_name){
            $.post( "/admin/users/get",{from:from,load_interval:load_interval})
            .done(function( res ) {
                if(res["out"] == "good"){
                    document.getElementById("users_count").innerText = res["count"];
                    res["body"].forEach(user => {
                        make_user(user,res);
                        user_count_check();
                    });
                }
                else if (res["out"] == "bad"){
                    
                }
            });
        }
        else{
            ask("имя",{func:(out)=>{
                if(out != null && out != "" && out != " "){
                    from = 0;
                    $.post( "/admin/users/find",{login:out,from:from,load_interval:load_interval})
                    .done(function( res ) {
                        if(res["out"] == "good"){
                            res["body"].forEach(user => {
                                make_user(user,res);
                            });
                        }
                        else if(res["out"] == "bad"){
                            msg("нет пользователя с таким иминем")
                            load_users_data(users_from);
                        }
                    });
                }
            }})
        }
        
        function make_user(user,res){
            let user_sec = document.createElement("li");user_sec.id = `user_${user["id"]}`;
            let user_name = document.createElement("div");user_name.id = `login_${user["id"]}`;user_name.innerText = user["login"];user_name.setAttribute("onclick",`user_edit("login",${user["id"]})`);user_name.classList.add("user_edit");
            let user_pass = document.createElement("div");user_pass.id = `pass_${user["id"]}`;user_pass.innerText = user["pass"];user_pass.classList.add("pass_blur"); user_pass.setAttribute("onclick",`user_edit("pass",${user["id"]})`);user_pass.classList.add("user_edit");
    
            let admin = find_admin(res["admins"],user["id"])
            // console.log(admin);
            let user_prevs = document.createElement("input");user_prevs.setAttribute("type","checkbox");;user_prevs.id = `admin_${user["id"]}`;user_prevs.checked = admin["admin"];user_prevs.setAttribute("onclick",`user_edit('admin',${user["id"]})`);user_prevs.classList.add("user_edit");
            let user_prevs_usr = document.createElement("input");user_prevs_usr.setAttribute("type","checkbox");;user_prevs_usr.id = `admin_usr_${user["id"]}`;user_prevs_usr.checked = admin["admin_usr"];user_prevs_usr.setAttribute("onclick",`admin_edit(${user["id"]})`);user_prevs_usr.classList.add("user_edit");
            let user_prevs_obj = document.createElement("input");user_prevs_obj.setAttribute("type","checkbox");user_prevs_obj.id = `admin_obj_${user["id"]}`;user_prevs_obj.checked = admin["admin_obj"];user_prevs_obj.setAttribute("onclick",`admin_edit(${user["id"]})`);user_prevs_obj.classList.add("user_edit");
            let user_del_btn = document.createElement("button");user_del_btn.id = `user_del_btn-${user["id"]}`; user_del_btn.innerText = "удалить"; user_del_btn.setAttribute("onclick",`user_del(${user["id"]})`); user_del_btn.classList.add("user_edit");user_del_btn.classList.add("btn_blue");
            if (JSON.parse(admin["admin"]) == true) {
                user_prevs_obj.style.pointerEvents = "all";
                user_prevs_usr.style.pointerEvents = "all";
            }
            else{
                user_prevs_obj.style.pointerEvents = "none";user_prevs_obj.checked = false;
                user_prevs_usr.style.pointerEvents = "none";user_prevs_usr.checked = false;
            }
    
            user_sec.append(user_name);user_sec.append(user_pass);
            user_sec.append(user_prevs);user_sec.append(user_prevs_usr);user_sec.append(user_prevs_obj);
            user_sec.append(user_del_btn);
            document.getElementById("user_list").append(user_sec);

        }
    }

    function find_admin(admins,id){
        if(Object.keys(admins).length > 0){
            rights = {admin:false,admin_usr:false,admin_obj:false};
            Object.entries(admins).forEach(([key,value]) => {
                // console.log(value);
                if(value["uid"] == parseInt(id) && rights != {}){
                    rights["admin"] = true;
                    if(value["rights"] == 3){
                        rights["admin_usr"] = true;
                        rights["admin_obj"] = true;
                        // return rights;
                    }
                    else if(value["rights"] == 1){
                        rights["admin_usr"] = false;
                        rights["admin_obj"] = true;
                        // return rights;
                    }
                    else if(value["rights"] == 2){
                        rights["admin_usr"] = true;
                        rights["admin_obj"] = false;
                        // return rights;
                    }
                }
                // if(key == Object.keys(admins).at(-1)){
                //     // console.log("end");
                //     rights["admin"] = false;
                //     rights["admin_obj"] = false;
                //     rights["admin_usr"] = false;
                //     // return rights;
                // }
            });
        }
        // console.log(rights,"asd");
        // return rights;
        // console.log(rights);
        return rights;
    }
    function user_edit(key,id,...args){
        // console.log(args);
        let login = document.getElementById(`login_${id}`).innerText;
        let admin = JSON.parse(document.getElementById(`admin_${id}`).checked);
        let pass= document.getElementById(`pass_${id}`).innerText;
        let value = null;
        if (key == 'login' || key == "pass") {
            ask(`изменение ${key} пользователя ${login}`,{def:document.getElementById(`${key}_${id}`).innerText,func:(out)=>{
                if(out != null && out != "" && out != " "){
                    make(out);
                }
            }});
        }
        else if (key == "admin"){
            value = admin;
            make(value)
        }
        else if (key == "rights"){
            value = args[0]["rights"];
            make(value)
        }
        function make(value){
            $.post( "/admin/users/edit",{key:key,value:value,id:id,login:login})
            .done(function( res ) {
                // console.log("serv reg");
                if(res["out"] == "good"){
                    load_users_data(users_from);
                }
                if(res["out"] == "bad"){
                    msg("пользователь с таким иминем уже есть",{type:"warning"})
                }
            });
        }
    }

    function change_admin_prevs(admin,id){
        if (admin) {
            document.getElementById(`admin_usr_${id}`).style.pointerEvents = "all";
            document.getElementById(`admin_obj_${id}`).style.pointerEvents = "all";
        }
        else{
            document.getElementById(`admin_usr_${id}`).style.pointerEvents = "none";
            document.getElementById(`admin_obj_${id}`).style.pointerEvents = "none";
            document.getElementById(`admin_usr_${id}`).checked = false;
            document.getElementById(`admin_obj_${id}`).checked = false;
        }
    }

    function admin_edit(id){
        let obj_right = document.getElementById(`admin_usr_${id}`).checked;
        let user_right = document.getElementById(`admin_obj_${id}`).checked;
        if(obj_right & user_right){
            rights = 3;
        }
        else if(obj_right){
            rights = 2;
        }
        else if(user_right){
            rights = 1;
        }
        else{
            rights = 0;
        }
        console.log(rights);
        user_edit("rights",id,{rights:rights})
    }
    function user_del(id){
        let login = document.getElementById(`login_${id}`).innerText;
        msg(`вы точно хотите удалить пользователя ${login}?`,{type:"ask",res:(out)=>{if(out){
                $.post( "/admin/users/delete",{login:login,id:id})
                .done(function( res ) {
                    if(res["out"] == "good"){
                        load_users_data(users_from);
                    }
                });
            }
        }})
    }

    let user_edit_menu = document.createElement("div");user_edit_menu.id = "user_edit_menu"; user_edit_menu.classList.add("cmenu"); 
    let user_chenge_name = document.createElement("button");user_chenge_name.innerHTML = "именить логин"; user_chenge_name.setAttribute("onclick","user_edit('login')"); 
    let user_chenge_pass = document.createElement("button");user_chenge_pass.innerHTML = "изменить пароль"; user_chenge_pass.setAttribute("onclick","user_edit('pass')"); 
    let user_chenge_prevs = document.createElement("button");user_chenge_prevs.innerHTML = "сменить привелегии";user_chenge_prevs.setAttribute("onclick","user_edit('admin')"); 
    let user_delete = document.createElement("button");user_delete.innerHTML = "удалить пользователя";user_delete.setAttribute("onclick","user_del()"); 
    user_edit_menu.append(user_chenge_name);user_edit_menu.append(user_chenge_pass);user_edit_menu.append(user_chenge_prevs);user_edit_menu.append(user_delete);document.body.append(user_edit_menu);
</script>
