import { ref } from 'vue';
import Server from './Server';

const UserStatus = ref(0);

function parseJwt(token) {
    return JSON.parse(atob(token.split('.')[1]));
}

function SetUser(token){
    localStorage.setItem('token', token);
    UserStatus.value = 1;
}

async function HasAdmin(){
    let response = await Server().get('/user/has-admin');
    return response.data.status != "init";
}

async function SetUserSetting(key, value){
    let user = GetUser();
    if(!user.settings) user.settings = {};
    user.settings[key] = value;
    const response = await Server().post('/user/update-settings', { settings: user.settings });
    return response.data.settings;
}

async function GetUserSetting(key){
    const response = await Server().get('/user/get-settings');
    if (response.data.settings)
        return response.data.settings[key];
    return undefined;
}

function GetUser(){
    const token = localStorage.getItem('token');

    if(token){
        const data = parseJwt(token);

        // Check if token is expired
        const now = Date.now() / 1000;
        if(now > data.exp){
            LogoutUser();
            return undefined;
        }

        return data;
    }
    return undefined;
}

function IsAdmin(){
    const user = GetUser();
    if(user){
        return user.admin;
    }
}

function LoadUser(){
    const token = localStorage.getItem('token');
    if(token) UserStatus.value = 1;
}

function LogoutUser(){
    localStorage.removeItem("token");
    localStorage.removeItem("selectedCampaignId");
    UserStatus.value = 0;
}

export {
    UserStatus,
    GetUser,
    SetUser,
    LoadUser,
    IsAdmin,
    LogoutUser,
    HasAdmin,
    GetUserSetting,
    SetUserSetting
}
