function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function login() {
    // tell the user the app is loading
    document.getElementById("loginSubmit").value = "Loading";
    // this.preventDefault();
    // get login details
    let name = document.getElementById("name").value;
    let password = document.getElementById("password").value;
    // request login
    let response = await fetch("/login", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            name: name,
            password: password
        })
    });
    // if failed red button
    // else switch screen
    if (response.status !== 200) {
        document.getElementById("loginSubmit").classList.add("error");
        document.getElementById("loginSubmit").value = "Failed";
        return;
    } else {
        // switch screen
        document.getElementById("login").setAttribute("style", "display: none;");
        document.getElementById("mainPage").setAttribute("style", "");
    }

    // store user data in session storage
    let data = await response.json();
    localStorage.setItem("uid", data.uid);
    localStorage.setItem("name", data.name);
    localStorage.setItem("role", data.role);

    // if role is admin, keep auto styling
    if (localStorage.getItem("role") !== "admin") {
        document.getElementById("addButton").setAttribute("style", "display: none;");
        document.getElementById("taskButton").classList.value = "half";
        document.getElementById("historyButton").classList.value = "half";
        document.getElementById("menu").classList.value = "flex two";
    }

    await populateScreen();
}

async function populateScreen() {
    // get task data
    let taskPage = document.getElementById("tasks");
    taskPage.innerHTML = "";
    let response = await fetch("/getTasks");
    let tasksRaw = await response.json();
    let tasks = tasksRaw.tasks;

    // get historical data
    let historyPage = document.getElementById("historyContent");
    historyPage.innerHTML = "";
    response = await fetch("/getHistory");
    let historyRaw = await response.json();
    let history = historyRaw.history;

    // get points data
    let statsPage = document.getElementById("statData");
    statsPage.innerText = "";
    response = await fetch("/getUserPoints");
    let statsRaw = await response.json();
    let stats = statsRaw.userPoints;

    // if it is a user make the tasks add points
    // or if admin make it do nothing
    if (localStorage.getItem("role") === "user") {
        try {
            for (let i = 0; i < tasks.length; i++) {
                taskPage.innerHTML += `
            <div id="${tasks[i].tid}" class="half" style="height: fit-content">
                <div class="button" onclick="completeTask(${tasks[i].tid})">
                    <p id="taskName">${tasks[i].name}</p>
                    <p id="${tasks[i].tid}-p">${tasks[i].points} points</p>
                </div>
            </div>`
            }
        } catch (e) {
            taskPage.innerHTML +=`<sub>such empty</sub>`
        }
    } else if (localStorage.getItem("role") === "admin") {
        try {
            for (let i = 0; i < tasks.length; i++) {
                taskPage.innerHTML += `
            <div id="${tasks[i].tid}" class="half" style="height: fit-content">
                <div class="button" disabled data-tooltip="Admins can't get points">
                    <p id="taskName">${tasks[i].name}</p>
                    <p id="${tasks[i].tid}-p">${tasks[i].points} points</p>
                </div>
            </div>`
            }
        } catch (e) {
            taskPage.innerHTML +=`<sub>such empty</sub>`
        }
    }

    try {
        for (let i = (history.length -1); i >= 0; i-=1) {
            historyPage.innerHTML += `
            <div class="full">
                <article class="card">
                    <header>
                        <p>User: ${history[i].user}</p>
                        <p>Task: ${history[i].task}</p>
                        <p>Time: ${history[i].time}</p>
                        <p>Points gained: ${history[i].pointsGained}</p>
                    </header>   
                </article>
            </div>`
        }
    } catch (e) {
        historyPage.innerHTML += `
        <sub>Such empty</sub>`
    }

    for (let i = 0; i < stats.length; i++) {
        // put user points in box
        statsPage.innerText += `${stats[i].name}: ${stats[i].points} \n`
    }
}

async function completeTask(taskID) {
    let points = document.getElementById(`${taskID}-p`).innerText.split(" ")[0];
    let time = new Date().toISOString().split(".")[0];
    let uid = localStorage.getItem("uid");
    await fetch("/completeTask", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            uid: Number(uid),
            tid: Number(taskID),
            time: time,
            pointsGained: Number(points)
        })
    });
}

async function switchScreen(button) {
    await populateScreen();
    document.getElementById("tasks").setAttribute("style", "display: none;");
    document.getElementById("history").setAttribute("style", "display: none;");
    document.getElementById("addTask").setAttribute("style", "display: none;");

    if (button === "task") {
        document.getElementById("tasks").setAttribute("style", "");
    } else if (button === "history") {
        document.getElementById("history").setAttribute("style", "");
    } else if (button === "add") {
        document.getElementById("addTask").setAttribute("style", "");
    }
}

async function newTask() {
    let points = document.getElementById(`newTaskPoints`);
    let name = document.getElementById(`newTaskName`);
    await fetch("/addTask", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            tid: 0,
            name: name.value,
            points: Number(points.value),
        })
    });
    points.value = "";
    name.value = "";
}

async function fastLog() {
    sleep(500);
    if (localStorage.getItem("uid") != null && localStorage.getItem("name") != null && localStorage.getItem("role") != null)  {
        document.getElementById("login").setAttribute("style", "display: none;");
        document.getElementById("mainPage").setAttribute("style", "");
        if (localStorage.getItem("role") !== "admin") {
            document.getElementById("addButton").setAttribute("style", "display: none;");
            document.getElementById("taskButton").classList.value = "half";
            document.getElementById("historyButton").classList.value = "half";
            document.getElementById("menu").classList.value = "flex two";
        }

        await populateScreen();
    } else {
        // do nothing
    }
}

fastLog();