export const state = () => ({
    page: 1,
    resultsPerPage: 3,
});


export const getters = {

    dataset: (state, rootGetters, rootState) => rootState.learning.columnsSorted.filter(el => el.display && !el.fixed),

    firstEntry: (state) => (state.page - 1) * state.resultsPerPage,
    lastEntry: (state, getters) => getters.firstEntry + state.resultsPerPage,

    subset: (state, getters) => getters.dataset.slice(getters.firstEntry, getters.lastEntry),

    isFirstPage: (state) => state.page === 1,
    isLastPage: (state, getters) => state.page === getters.totalPages,
    totalPages: (state, getters) => Math.ceil(getters.dataset.length / state.resultsPerPage) || 1,

}

export const actions = {

    async changePage({ commit, state, getters }, direction) {

        if (!['previous', 'next'].includes(direction)) return

        const currentPage = state.page

        let newPage;

        if ((direction === 'next') && !getters.isLastPage) newPage = currentPage + 1
        if ((direction === 'previous') && !getters.isFirstPage) newPage = currentPage - 1


        await commit('SET_PAGE', newPage);
    },

}

export const mutations = {
    SET_PAGE: (state, page) => state.page = +page,
}