function loginError(message, code = null) {
    let errorStr;
    if (code) {
        errorStr = `Status code ${code}: ${message}`;
    } else {
        errorStr = message;
    }

    document.getElementById("error-text").textContent = errorStr;

    document.getElementById("login-error").style.display = "block";
}

async function generateToken(username, password) {
    const credentials = btoa(`${username} ${password}`);

    let response;
    try {
        response = await fetch("https://account.spfn.net/api/v2/oauth2/generate_token", {
            method: "GET",
            headers: {
                "Authorization": `Basic ${credentials}`,
            }
        })
    } catch (err) {
        loginError(`Internal Server Error: ${err.message}`)
        throw new Error(err);
    }

    if (!response.ok) {
        if (response.status == 400) { // Invalid Login
            loginError("Invalid SFID or Password");
        } else {
            loginError(await response.text(), response.status);
        }

        throw new Error("Network Response was not okay when Generating Token");
    };
    
    const data = await response.json();

    sessionStorage.setItem("authToken", data["token"])

    const expiry = data["expiry"].slice(0, 19) + "Z"
    sessionStorage.setItem("authExpires", expiry)
    return data["token"];
}

async function getToken(username, password) {
    let token = sessionStorage.getItem("authToken");

    let expiryStr = sessionStorage.getItem("authExpires");
    if (expiryStr) { // Expiry exists so token should exist
        let expiry = new Date(expiryStr);
        if (expiry < new Date()) { // Expired token
            token = await generateToken(username, password);
        } else if (!token) { // Expiry Saved but No Token (shouldn't be possible but it'll be caught if it happens)
            token = await generateToken(username, password);
        }
    } else { // Token Never Saved in Session
        token = await generateToken(username, password);
    }

    return token
}

document.getElementById("login").addEventListener("submit", async function(event) {
    event.preventDefault();

    document.getElementById("login-error").style.display = "none";

    const username = await document.getElementById("username").value;
    const password = await document.getElementById("password").value;
    
    let token = await getToken(username, password);
    if (!token) return;

    document.getElementById("password").value = "";

    // Go Back to Origin Page
    const params = new URLSearchParams(window.location.search);
    const redirectURL = params.get("redirect")

    window.location.href = redirectURL;
})

window.onload = async function () { // Check if the token expired
    let expiryStr = sessionStorage.getItem("authExpires");
    if (expiryStr) {
        let expiry = new Date(expiryStr);

        if (expiry < new Date()) { // Expired - Tell the user it expired
            loginError("Login Expired - Please Log In Again")
        }
    }
}