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

verifyLogin();
const token = window.localStorage.getItem("token");

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

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


async function fetchPersonalInformation() {
    const userData = await postData("/getInfo", {}, token);
    
    console.log(userData);

    document.getElementById("usernameField").textContent = userData.Username;
    document.getElementById("firstNameField").value = userData.FirstName;
    document.getElementById("lastNameField").value = userData.LastName;
    document.getElementById("dobField").value = userData.DOB.split("T")[0];
    
    return userData
}

const userData = fetchPersonalInformation();

async function updatePersonalInformation(e) {
    console.log(verifyLogin());
    e.preventDefault();
    const userData = {
        firstName: document.getElementById("firstNameField").value,
        lastName: document.getElementById("lastNameField").value,
        dob: document.getElementById("dobField").value
    }
    console.log(userData.dob);
    const resultObject = await postData("/setInfo", userData, token);
    

    if (resultObject.message.includes("success")) {
        error.style.display = "none";
        success.style.display = "flex";
    } else {
        errorMessage.innerHTML = resultObject.message;
        error.style.display = "flex";
    }

    
    window.localStorage.setItem("token", resultObject.token);
}

infoForm.onsubmit = updatePersonalInformation;
