import { doFetchCmsList, doFetchPageList } from '@/services/cache.service';
import { getField, updateField } from 'vuex-map-fields';
import humps from 'lodash-humps';

export const layout = {
    namespaced: true,
    state: {
        user: {
            userVisits: localStorage.getItem('cr_userVisitCount') ? localStorage.getItem('cr_userVisitCount') : 0
        },
        categoryQueryParam: {
            pageSize: '',
            pageNo: '',
            sortSelect: '',
            categoryId: '',
            search: '',
            sideFilter: ''
        },
        inProgress: false,
        heroContent: {},
        cmsBlockContent:{},
        snackbar: {
            show: false,
            message: null,
            color: null,
            timeout: 0
        },
        pageContent:{}
    },
    getters: {
        getField,
    },
    mutations: {
        updateField,
        inProgress(state, yesOrNo) {
            state.inProgress = yesOrNo
        },
        setCategoryQueryParam(state, data) {
            state.categoryQueryParam = data;
        },
        setHeroContent(state, content) {
            state.heroContent = content
        },
        setCmsBlockContent(state, content) {
            state.cmsBlockContent = content
        },
        setPageContent(state, content) {
            state.pageContent = content
        },
        setSnackbar(state, obj) {
            state.snackbar = obj;
        },
    },
    actions: {
        updateCategoryQueryParam({ commit }, values) {
            commit('setCategoryQueryParam', values);
        },       
        showSnackbar({ commit }, obj) {
            commit('setSnackbar', obj);
        },
        setHeroContent({ commit }, one) {
            commit('setHeroContent', humps(one));
        },
        fetchCmsBlock: async({ commit }) => {
            try {
                commit('inProgress', true);
                const blockContent = await doFetchCmsList();
                if (blockContent) {
                    commit('inProgress', false);
                    commit('setCmsBlockContent', humps(blockContent));
                }
            } catch (error) {
                commit('inProgress', false);
                throw error
            }
        },
        fetchPageContent: async({ commit }) => {
            try {
                commit('inProgress', true);
                const pageContent = await doFetchPageList();
                if (pageContent) {
                    commit('inProgress', false);
                    commit('setPageContent', humps(pageContent));
                }
            } catch (error) {
                commit('inProgress', false);
                throw error
            }
        },
    }

};