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

import Vue from 'vue'

import { MGQ } from 'vuejs/api/graphql-axios'
import { print } from 'graphql/language/printer'
import gql from 'graphql-tag'
import searchresultGQL from 'vuejs/api/gql/searchresults.fragment.gql'

export default {
  namespaced: true,

  // initial state
  state: {
    keys: '',
    term: '',
    uuids: [],
    items: [],
    offset: 0,
    limit: 15,
    infos: null,
    count: 0,
    noresults: false,
    // infinteState will come from vue-infinite-loading plugin
    // implemented in vuejs/components/Content/Base.vue
    infiniteLoadingState: null
  },

  // getters
  getters: {},

  // mutations
  mutations: {
    setUuids (state, uuids) {
      state.uuids = state.uuids.concat(uuids)
    },
    resetUuids (state) {
      state.uuids = []
    },
    setResults (state, items) {
      // console.log('setResults, items', items);
      if(items){ // avoid bug like items = [null]
        state.items = state.items.concat(items)
      }
      // console.log('setResults, state.items', state.items);
    },
    updateItem (state, item) {
      // state.items[data.index] = data.item // this is not triggering vuejs refresh
      // find the right index
      const index = state.items.findIndex(i => i.id === item.id)
      // update the array
      if (index !== -1) {
        Vue.set(state.items, index, item)
      }
      // console.log("mutation updateItem state.items", state.items)
    },
    resetItems (state) {
      state.items = []
    },
    setKeys (state, keys) {
      state.keys = keys
    },
    setTerm (state, term) {
      state.term = term
    },
    setInfos (state, infos) {
      state.infos = infos
    },
    setCount (state, count) {
      state.count = count
    },
    resetCount (state, count) {
      state.count = false
    },
    setNoresults (state) {
      state.noresults = true
    },
    resetNoresults (state) {
      state.noresults = false
    },
    resetOffset (state) {
      state.offset = 0
    },
    incrementOffset (state) {
      state.offset += state.limit
    },
    setInfiniteState (state, infiniteLoadingstate) {
      state.infiniteLoadingState = infiniteLoadingstate
    }
  },

  // actions
  actions: {
    newSearch ({ dispatch, commit, state }) {
      console.log('Search newSearch')
      commit('resetUuids')
      commit('resetItems')
      commit('resetCount')
      commit('resetNoresults')
      commit('resetOffset')
      if(state.keys || state.term){
        this.commit('Common/setPagetitle', state.keys)
      }else{
        this.commit('Common/setPagetitle', 'Base')
      }
      dispatch('getResults')
    },
    nextPage ({ dispatch, commit, state }, $infiniteLoadingstate) {
      console.log('Search nextPage', $infiniteLoadingstate)
      commit('incrementOffset')
      commit('setInfiniteState', $infiniteLoadingstate)
      dispatch('getResults')
    },
    getResults ({ dispatch, commit, state }) {
      const params = {
        keys: state.keys,
        term: state.term,
        offset: state.offset,
        limit: state.limit
      }
      // console.log('Search getResults params', params);
      const q = qs.stringify(params)
      return MA.get('/materio_sapi/getresults?' + q)
        .then(({ data }) => {
          console.log('search MA getresults data', data)
          // commit('setItems', data.items)
          commit('setInfos', data.infos)
          commit('setCount', data.count)
          if (data.count) {
            commit('setUuids', data.uuids)
            // loadMaterials is on mixins
            // https://github.com/huybuidac/vuex-extensions
            // dispatch('loadMaterialsGQL', {
            //   ids: data.nids,
            //   gqlfragment: materiauGQL,
            //   callBack: 'loadSearchResultsCallBack'
            // })
            let ast = gql`{
              searchresults(ids: [${data.nids}], lang: "${drupalDecoupled.lang_code}") {
                ...SearchResultFields
              }
            }
            ${ searchresultGQL }
            `
            MGQ.post('', { query: print(ast) })
              .then(resp => {
                console.log('loadSearchResultsGQL resp', resp )
                dispatch("loadSearchResultsCallBack", { items: resp.data.data.searchresults})
              })
              .catch(error => {
                console.warn('Issue with loadSearchResults', error)
                Promise.reject(error)
              })
          } else {
            commit('setNoresults')
          }
        })
        .catch((error) => {
          console.warn('Issue with getResults', error)
          Promise.reject(error)
        })
    },
    loadSearchResultsCallBack ({ commit, state }, { items, callBackArgs }) {
      console.log('search loadSearchResultsCallBack', items)
      commit('setResults', items)
      if (state.infiniteLoadingState) {
        if (state.offset + state.limit > state.count) {
          console.log('Search infinite completed')
          // tell to vue-infinite-loading plugin that there si no new page
          state.infiniteLoadingState.complete()
        } else {
          console.log('Search infinite loaded')
          // tell to vue-infinite-loading plugin that newpage is loaded
          state.infiniteLoadingState.loaded()
        }
      }
    },
    refreshItem({ commit, state }, { id }) {
      console.log("Search refreshItem: id", id);
      let ast = gql`{
        searchresult(id: ${id}, lang: "${drupalDecoupled.lang_code}") {
          ...SearchResultFields
        }
      }
      ${ searchresultGQL }
      `
      MGQ.post('', { query: print(ast) })
        .then(resp => {
          console.log('refreshItem searchresult resp', resp )
          // dispatch("loadSearchResultsCallBack", { items: resp.data.data.searchresults})
          commit("updateItem", resp.data.data.searchresult)
        })
        .catch(error => {
          console.warn('Issue with refreshItem', error)
          Promise.reject(error)
        })
    }
  }
}
