import {
    createUser, deleteUser, getAllUsers, getUser, updateUser,
} from "./restApi";
import {
    cntrls, createTableRow,
} from "./ui";

async function drawUsersTable() {
    console.info("Try to load data");
    if (!cntrls.table) {
        return;
    }
    const data = await getAllUsers();
    cntrls.table.innerHTML = "";
    data.forEach((user, index) => {
        cntrls.table.appendChild(
            createTableRow(
                user,
                index,
                () => location.assign(`page-edit.html?id=${user.id}`),
                () => removeUser(user.id),
            ),
        );
    });
}

async function addUser(_handle, _email, _password) {
    console.info("Try to add user");
    const data = await createUser(_handle,_email,_password);
    console.info("Added");
    console.info(data);
    drawUsersTable();
}

async function editUser(id, _handle, _email, _password) {
    console.info("Try to update user");
    const data = await updateUser(id, _handle, _email, _password);
    console.info("Updated");
    console.info(data);
    drawUsersTable();
}

async function removeUser(id) {
    if (!confirm("Do you really want to remove this user?")) {
        console.info("Canceled");
        return;
    }
    console.info("Try to remove item");
    const data = await deleteUser(id);
    console.info(data);
    drawUsersTable();
}

async function readFile(file) {
    const reader = new FileReader();

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

        reader.onloadend = () => {
            const fileContent = reader.result;
            resolve(fileContent);
        };
        reader.onerror = () => {
            reject(new Error("oops, something went wrong with the file reader."));
        };
        reader.readAsDataURL(file);
    });
}

function checkValidation(){
    let reg = /\w+@+\w+\.+\w/gi;
    let flag = false;
    if(!reg.test(cntrls.email.value)){
        cntrls.email.style.background = "red";
        cntrls.email.focus();
        flag = true;
    }
    else{
        email.style.background = "white";
    }
    reg = /^\w*$/gi;
    if(!reg.test(cntrls.handle.value)){
        cntrls.handle.style.background = "red";
        cntrls.handle.focus();
        flag = true;
    }
    else{
        console.log(1);
        handle.style.background = "white";
    }
    reg = /^\w*$/gi;
    if(!reg.test(cntrls.password.value)){
        cntrls.password.style.background = "red";
        cntrls.password.focus();
        flag = true;
    }
    else{
        password.style.background = "white";
    }
    return flag == false;
}

export async function usersForm() {
    console.info("usersForm");
    drawUsersTable();
    const goBack = () => location.assign("/AdminPage.html");
    const urlParams = new URLSearchParams(location.search);
    const currentId = urlParams.get("id");
    if(currentId){
        const data = await getUser(currentId);
        console.log(data);
        cntrls.handle.value = data.handle;
        cntrls.email.value = data.email;
        cntrls.password.value = data.password;
    }

    cntrls.form.addEventListener("submit", async (event) => {
        
        console.info("Form onSubmit");
        event.preventDefault();
        event.stopPropagation();
        if(!checkValidation()){
            return;
        }
        if (!currentId) {
            await addUser(
                cntrls.handle.value,
                cntrls.email.value,
                cntrls.password.value,
            );
        } else {
            await editUser(
                currentId,
                cntrls.handle.value,
                cntrls.email.value,
                cntrls.password.value,
            );
        }
        goBack();
    });
}