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

export default {
  namespaced: true,

  // initial state
  state : {
    keys: "",
    term: "",
    uuids: [],
    items: [],
    offset: 0,
    limit: 15,
    infos: null,
    count: 0,
    // 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 = []
    },
    setItems (state, items) {
      state.items = state.items.concat(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
    },
    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('resetOffset')
      this.commit('Common/setPagetitle', state.keys)
      dispatch('getResults')
    },
    nextPage ({ dispatch, commit, state }, $infiniteLoadingstate) {
      console.log("Search nextPage", $infiniteLoadingstate);
      commit('incrementOffset')
      commit('setInfiniteState', $infiniteLoadingstate)
      dispatch('getResults')
    },
    getResults ({ dispatch, commit, state }) {
      let params = {
        keys: state.keys,
        term: state.term,
        offset:state.offset,
        limit: state.limit
      }
      // console.log('Search getResults params', params);
      let 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)
          commit('setUuids', data.uuids)
          dispatch('getItems', data.uuids)
        })
        .catch(( error ) => {
            console.warn('Issue with getResults', error)
            Promise.reject(error)
        })
    },
    getItems({ dispatch, commit, state }, uuids) {
      let params = {
        // include: 'images', // no needs to include thanks to consumers_image_styles module
        'filter[uuids-groupe][group][conjunction]': 'OR'
      };
      for (var i = 0; i < uuids.length; i++) {
        let uuid = uuids[i]
        params[`filter[${uuid}][condition][path]`] = 'id'
        params[`filter[${uuid}][condition][value]`] = uuid
        params[`filter[${uuid}][condition][operator]`] = '='
        params[`filter[${uuid}][condition][memberOf]`] = 'uuids-groupe'
      }
      // console.log('search JSONAPI params', params);
      let q = qs.stringify(params)
      return JSONAPI.get('node/materiau?'+q)
        .then(({ data }) => {
          console.log('search getItems data', data)
          dispatch('parseItems', {data:data.data, uuids:uuids})
          // commit('setItems', data.items)
        })
        .catch(( error ) => {
            console.warn('Issue with getItems', error)
            Promise.reject(error)
        })
    },
    parseItems({ dispatch, commit, state }, { data, uuids }) {
      // data comes from jsonapi query
      // uuids comes from solr search query (we loop from uuids to conserve the search results order)
      console.log('search parseItems data, uuids', data, uuids)
      let items = []
      // for (var i = 0; i < data.length; i++) {
      for (var i = 0; i < uuids.length; i++) {
        let uuid = uuids[i]
        // https://stackoverflow.com/questions/11258077/how-to-find-index-of-an-object-by-key-and-value-in-an-javascript-array
        let item_index = data.findIndex(p => p.id == uuid)
        let item_src = data[item_index]
        let attrs = item_src.attributes
        let relations = item_src.relationships

        // get field values
        let item = {
          uuid: uuid,
          title: attrs.title,
          field_short_description: attrs.field_short_description,
          body: attrs.body,
          field_reference: attrs.field_reference,
        }

        // get images included values
        let img_src = relations.images.data
        item.images = []
        for (var j = 0; j < img_src.length; j++) {
          item.images.push({
            title: img_src[j].meta.title,
            // meta.imageDerivatives.style.href link is provided by drupal consumers_image_styles module
            url: img_src[j].meta.imageDerivatives.links.card_medium.href
          })
        }

        items.push(item)
      }
      console.log('items', items)
      commit('setItems', 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()
        }
      }
    }
  }
}
