import { useAppStore } from '@/stores/app';

const debounceData = [];

export default {
    data(){
        return {
            store: null,
        }
    },
    created(){
        this.store = useAppStore();
    },
    computed: {
        user: {
            get() {
                return this.store.user;
            },
            set(value) {
                this.store.user = value;
            }
        },
        roles(){
            let roles = {};
            this.user && this.user.roles && this.user.roles.forEach(r=>{
                roles[r] = true;
            })
            return roles;
        },
    },
    methods: {
        async loadUser() {
            let response = await this.$api.user.load();
            this.user = response.data.user;
            return this.user;
        },
        getErrorText(error){
            let msg = error?.response?.data?.error || error?.message;
            if (msg){
                if (typeof msg == 'object'){
                    return JSON.stringify(msg);
                }else if (this.l.errors[msg]) {
                    return this.l.errors[msg]
                }else {
                    return msg;
                }
            }else{
                return error;
            }
        },
        toast(text, color, timeout=3000){
            this.store.snackbar.text = text;
            this.store.snackbar.color = color;
            this.store.snackbar.timeout = timeout;
            this.store.snackbar.show = true;
        },
        debug(...args){
            if (this.store?.prefs?.debug){
                console.log(...args);
            }
        },
        debounce(fn){
            let f = debounceData.find(f=>f.fn == fn);
            if (f){
                clearTimeout(f.to);
            }else{
                f = {fn};
                debounceData.push(f);
            }
            f.to = setTimeout(...arguments);
        },
    }
}