export const user = $state({
    name : null,
    theme : 'default'
})

export const timetrack = $state({running:null});



export async function checkUser(){
    let url  = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/whoami`;
    let resp = await fetch(url,{credentials: 'include'});
    if (resp.ok){
        const json = await resp.json();
        for (let key of Object.keys(json)) user[key] = json[key];
        url  = `${location.protocol}//${location.host.replace('5173','8080')}/api/time/started`;
        resp = await fetch(url,{credentials: 'include'});
    } else {
        user.name = null;
    }
    if (resp.ok){
        const track = await resp.json();
        timetrack.running = track;
    }
}

export async function logout(){
    const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/logout`;
    await fetch(url,{
        credentials: 'include'
    });
    timetrack.running = null;
    user.name = null;
}

export async function tryLogin(credentials){
    const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/login`;
    let response = await fetch(url,{
        credentials: 'include',
        headers: {
            'Content-Type':'application/json'
        },
        method: 'POST',
        body: JSON.stringify(credentials)
    });
    if (response.ok){
        const json = await response.json();
        for (let key of Object.keys(json)) user[key] = json[key];
        return null;
    } else {
        alert("Login failed!");
        let json = await response.json();
        return json;
    }
}