import { defineStore } from 'pinia'
import { print } from 'graphql/language/printer'
import gql from 'graphql-tag'

// import REST from '@api/rest-axios'
import GQL from '@api/graphql-axios'
// import JSONAPI from '@api/json-axios'
import MA from '@api/ma-axios'

import qs from 'querystring-es3'

import ResultsConcernementFields from '@api/gql/results_concernement.fragment.gql'
import ResultsEntiteFields from '@api/gql/results_entite.fragment.gql'

export const SearchStore = defineStore({
  id: 'search',
  state: () => ({
    phrase: null,
    contentTypeFilter: 'concernements',
    results: null,
    loaded_results: null
  }),
  getters: {
    
  },
  actions: {
    setSearchValue (value) {
      console.log('setSearchValue', value);
      if (value) {
        this.phrase = value;
      }
    },
    setContentType (v) {
      this.contentTypeFilter = v
    },
    newSearch () {
      console.log('search store loadResults', this.keys);
      // this.keys = keys;
      const params = {
        phrase: this.phrase,
        content_type: this.contentTypeFilter
      }
      const q = qs.stringify(params)
      return MA.get('/ouatt_searchapi/getresults?' + q)
        .then(({ data }) => {
          console.log('search MA getresults data', data, data.nids)
          this.results = data;
          this.loadeResults();
        })
        .catch((error) => {
          console.warn('Issue with getResults', error)
          // window.location.reload()
          Promise.reject(error)
        })
    },
    loadeResults () {
      return new Promise((resolve, reject) => {
        let ast;
        if (this.contentTypeFilter === 'entites') {
          ast = gql`{
            entites(ids: [${this.results.nids}]) {
              ...ResultsEntiteFields
            }
          }
          ${ResultsEntiteFields}
          `
          GQL.post('', { query: print(ast) })
            .then(({ data : { data  : { entites } } }) => {
              console.log('entites all loaded', entites)
              this.loaded_results = entites
            })
            .catch(error => {
              console.warn('Issue with loadResults', error)
              Promise.reject(error)
            })
        } else {
          ast = gql`{
            concernements(ids: [${this.results.nids}]) {
              ...ResultsConcernementFields
            }
          }
          ${ResultsConcernementFields}
          `

          GQL.post('', { query: print(ast) })
            .then(({ data : { data  : { concernements } } }) => {
              console.log('concernements all loaded', concernements)
              this.loaded_results = concernements
            })
            .catch(error => {
              console.warn('Issue with loadResults', error)
              Promise.reject(error)
            })
        }
        // console.log('ast', ast);
      }) 
    }
  }
})