import { postData } from "./client.js";

const loginForm = document.getElementById("loginForm");

const error = document.querySelector(".error");
const errorMessage = document.querySelector(".error p");
const success = document.querySelector(".success");

if (loginForm) loginForm.onsubmit = async e => {
    e.preventDefault();
    let resultObject = await postData("/login", {
        username: document.getElementById("logUser").value,
        password: document.getElementById("logPass").value
    });
    if (resultObject.message.includes("success")) {
        error.style.display = "none";
        success.style.display = "flex";
    } else {
        errorMessage.innerHTML = resultObject.message;
        error.style.display = "flex";
    }
    if (resultObject.success) {
        window.location.href = "/home"
        localStorage.setItem("token", resultObject.token);
    }
};
