import { useState } from './useState';
import { useRole } from './useRole';
import { useUserConfig } from './useUserConfig';


export function useSession() {
    function getToken() {
        const localToken = localStorage.getItem('token');
        const sessionToken = sessionStorage.getItem('token');

        return localToken || sessionToken || '';
    }

    function setToken(data) {
        if (data.keepLogin) {
            localStorage.setItem('token', data.token);
        } else {
            sessionStorage.setItem('token', data.token);
        }
    }

    function destroy() {
        if (localStorage.getItem('token'))
            localStorage.removeItem('token')

        if (sessionStorage.getItem('token'))
            sessionStorage.removeItem('token');

        const { setUser } = useState();

        setUser({
            id: 0,
            name: '',
            nickname: '',
            lang: '',
            darkMode: null,
        });
    }

    async function login(token, keepLogin) {
        setToken({ token, keepLogin });

        await useRole().fetch();
        await useUserConfig().fetch();
    }

    function isLoggedIn() {
        const localToken = localStorage.getItem('token');
        const sessionToken = sessionStorage.getItem('token');

        return !!(localToken || sessionToken);
    }

    return {
        getToken,
        setToken,
        destroy,
        login,
        isLoggedIn,
    };
}
