import { JSONAPI } from 'vuejs/api/json-axios'
import { REST } from 'vuejs/api/rest-axios'
import { MA } from 'vuejs/api/ma-axios'
import qs from 'querystring'

export default {
  namespaced: true,

  // initial state
  state : {
    contenttype:null,
    items: [],
    page: 0,
    // infinteState will come from vue-infinite-loading plugin
    // implemented in vuejs/components/Content/Base.vue
    infiniteLoadingState: null
  },

  // getters
  getters : {},

  // mutations
  mutations : {
    setItems (state, items) {
      state.items = state.items.concat(items)
    },
    incrementPage(state){
      state.page += 1;
    },
    setInfiniteState(state, infiniteLoadingstate){
      state.infiniteLoadingState = infiniteLoadingstate
    }
  },

  // actions
  actions : {
    getItems({ dispatch, commit, state }){
      // if(!state.contenttype){
      //   REST.get('/entity/node_type/article?_format=json', {})
      //   .then(({ data }) => {
      //     console.log('blabla REST contenttype : data', data);
      //   })
      //   .catch(( error ) => {
      //       console.warn('Issue with blabla contenttype', error)
      //       Promise.reject(error)
      //   })
      // }
      return REST.get(`/blabla_rest?_format=json&page=${state.page}`, {})
        .then(({ data }) => {
          console.log('blabla REST: data', data)
          if(data.length){
            commit('setItems',data)
            // console.log('items.length', this.items.length);
            if(state.infiniteLoadingState)
              state.infiniteLoadingState.loaded()
          }else{
            if(state.infiniteLoadingState)
              state.infiniteLoadingState.complete()
          }
        })
        .catch(( error ) => {
            console.warn('Issue with blabla getitems', error)
            Promise.reject(error)
        })
    },
    nextPage ({ dispatch, commit, state }, $infiniteLoadingstate) {
      console.log("blabla nextPage", $infiniteLoadingstate);
      commit('incrementPage')
      commit('setInfiniteState', $infiniteLoadingstate)
      dispatch('getItems')
    },
    getItemIndex({ dispatch, commit, state}, uuid) {
      return state.items.findIndex((e) =>{
        return e.uuid == uuid
      })
    },
    getPrevNextItems({ dispatch, commit, state }, index) {
      return {
        prev:state.items[index-1],
        next:state.items[index+1]
      }
    }
  }
}
