import { ref } from 'vue';
import { defineStore } from 'pinia';

export const useArrayDataStore = defineStore('arrayDataStore', () => {
    const state = ref({});
    const defaultOpts = {
        filter: {},
        userFilter: {},
        userParams: {},
        url: '',
        limit: 10,
        skip: 0,
        order: '',
        isLoading: false,
        userParamsChanged: false,
        exprBuilder: null,
        searchUrl: 'params',
        navigate: null,
        page: 1,
    };

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

    function set(key) {
        state.value[key] = getDefaultState();
    }

    function clear(key) {
        delete state.value[key];
    }

    function reset(key, opts = []) {
        if (!opts.length) state.value[key] = getDefaultState();
        else
            opts.forEach((opt) => {
                if (opt.includes('.')) {
                    const [parent, child] = opt.split('.');
                    state.value[key][parent][child] = defaultOpts[child];
                } else if (Object.hasOwn(state.value[key], opt))
                    state.value[key][opt] = defaultOpts[opt];
            });
    }

    function getDefaultState() {
        return Object.assign(JSON.parse(JSON.stringify(defaultOpts)), {
            data: ref(),
        });
    }

    return {
        get,
        set,
        clear,
        reset,
    };
});
