import { ref, computed } from 'vue';

const state = ref({});

const user = ref({
    id: 0,
    name: '',
    nickname: '',
    lang: '',
    darkMode: null,
    companyFk: null,
    warehouseFk: null,
});
if (sessionStorage.getItem('user'))
    user.value = JSON.parse(sessionStorage.getItem('user'));

const roles = ref([]);
const acls = ref([]);
const tokenConfig = ref({});
const drawer = ref(true);
const headerMounted = ref(false);

export function useState() {
    function getUser() {
        return computed(() => {
            return user.value;
        });
    }

    function setUser(data) {
        const currentUser = { ...JSON.parse(sessionStorage.getItem('user')), ...data };
        sessionStorage.setItem('user', JSON.stringify(currentUser));
        user.value = currentUser;
        return currentUser;
    }

    function getRoles() {
        return computed(() => {
            return roles.value;
        });
    }

    function setRoles(data) {
        roles.value = data;
    }

    function getAcls() {
        return computed(() => acls.value);
    }

    function setAcls(data) {
        acls.value = data;
    }
    function getTokenConfig() {
        return computed(() => {
            return tokenConfig.value;
        });
    }

    function setTokenConfig(data) {
        tokenConfig.value = data;
    }

    function set(name, data) {
        state.value[name] = ref(data);
    }

    function get(name) {
        return state.value[name];
    }

    function unset(name) {
        delete state.value[name];
    }

    return {
        getUser,
        setUser,
        getRoles,
        setRoles,
        getAcls,
        setAcls,
        getTokenConfig,
        setTokenConfig,
        set,
        get,
        unset,
        drawer,
        headerMounted,
    };
}
