/* Coded by L1ghtM3n@protonmail.com */

function Login() {
    // Get data from form
    let username = document.getElementById("username_input").value;
    let password = document.getElementById("password_input").value;
    // Create request
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    formData.append("username", username)
    formData.append("password", password)
    // Send request
    xhr.open("POST", "api/login", false);
    xhr.send(formData);
    // Handle server error
    if (xhr.status !== 200) {
        swal(xhr.status, xhr.statusText, "error");
        return false;
    }
    // Parse server response
    let response = JSON.parse(xhr.responseText);
    let icon = response["error"] ? "error" : "success";
    // Show server response
    swal("Server", response["message"], icon);
    // Redirect to dashboard
    if (response["error"] === false) {
        setTimeout(() =>
            location.href = "/dashboard?welcome",
            1500
        );
    }
    // Done
    return !response["error"];
}

// Trigger login button when 'ENTER' key is pressed
document.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        Login();
    }
});
