import { defineStore } from 'pinia'
// import REST from '@api/rest-axios'
// import JSONAPI from '@api/json-axios'
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 ConcernementFields from '@api/gql/concernement.fragment.gql'
// import EntityFields from '@api/gql/entitydef.fragment.gql'

export const ConcernementsStore = defineStore({
  id: 'concernements',
  state: () => ({
    map_mode: null,
    concernements: [],
    concernementsByID: {},
    allEntitesById: {},
    allBesoinsById: {},
    opened_concernement: false,
    opened_entite_id: null,
    ct_concernement: {},
    ct_entite: {},
    ct_cercle_politique: {},
    p_groupes_interets: {},
    p_reception_et_traitement: {},
    p_mise_en_oeuvre_decision: {},
    p_reception_application_decision: {},
    concernements_loaded: false,
  }),
  getters: {
    
  },
  actions: {
    setMapMode(mode) {
      console.log(`set map_mode ${mode}`);
      // mode can be : terraindevie, proximite, superposition, puissancedagir, action, doleancer
      this.map_mode = mode;
    },
    loadConcernements () {
      console.log('concernements store loadConcernements');
      return new Promise((resolve, reject) => {
        const ast = gql`{
          allconcernements {
            ...ConcernementFields
          }
        }
        ${ConcernementFields}
        `
        // console.log('ast', ast);
        GQL.post('', { query: print(ast) })
          .then(({ data : { data  : { allconcernements } } }) => {
            console.log('loadconcernements loaded', allconcernements)
            this.concernements = [];
            // parse concernements
            allconcernements.forEach(concernement => {
              concernement.visible = true;

              concernement.entites_byid = {};
              concernement.entitesagissantes_byid = {};
              concernement.has_agissantes = false;
              var entites_temp = concernement.entites; // record a temp entites liste
              concernement.entites = []; // erase the concernement.entite array as we want to keep only visible entites
              entites_temp.forEach(entite => {
                if (entite.entite) { // entite.entite may be null because of workflow confidentiality
                  concernement.entites_byid[entite.entite.id] = entite;
                  // record entite agissante
                  if (entite.entite.agissante) {
                    concernement.entitesagissantes_byid[entite.entite.id] = entite;
                    concernement.has_agissantes = true;
                  }
                  // record a flat list of all entités of all concernement for map-popup
                  this.allEntitesById[entite.entite.id] = entite;
                  concernement.entites.push(entite); // fill the entites array with visible entite only
                }
              });
              
              // puissance d'agir
              concernement.has_puissancedagir = concernement.besoins.length ? true : false;
              concernement.besoins.forEach(besoin => {
                this.allBesoinsById[besoin.id] = besoin;
              });

              // doleance
              concernement.has_doleance = concernement.doleances.length ? true : false;
              
              // recit
              concernement.has_recit = concernement.recit !== null;

              // common
              this.concernements.push(concernement);
              this.concernementsByID[concernement.id] = concernement;

            });
            this.concernements_loaded = true;
          })
          .catch(error => {
            console.warn('Issue with loadConcernements', error)
            Promise.reject(error)
          })
      })
    },
    reloadConcernements () {
      console.log('reloadConcernements');
      // reset the arrays
      this.concernements = [];
      this.concernementsByID = {};
      this.concernements_loaded = false;
      this.loadConcernements();
    },
    loadContentTypeDefinition () {
      const body = {
        query: `
          query EntityDef($type: String!, $bundle: String!){
            entitydef(type: $type, bundle: $bundle) {
              fields {
                type
                field_name
                label
                description
              }
            }
          }`,
        variables: {}
      } 

      // concernement
      body.variables = { type: 'node', bundle: 'concernement' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.ct_concernement[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef concernement', this.ct_concernement);
          
        })

      // entite
      body.variables = { type: 'node', bundle: 'entite' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.ct_entite[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef entite', this.ct_entite);
          
        })

      // cercle_politique
      body.variables = { type: 'node', bundle: 'cercle_politique' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.ct_cercle_politique[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef cercle_politique', this.ct_cercle_politique);
          
        })

      // paragraphe groupes_interets
      body.variables = { type: 'paragraph', bundle: 'groupes_interets' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_groupes_interets[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_groupes_interets', this.p_groupes_interets);
          
        })

      // paragraphe reception_et_traitement
      body.variables = { type: 'paragraph', bundle: 'reception_et_traitement' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_reception_et_traitement[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_reception_et_traitement', this.p_reception_et_traitement);
          
        })

      // paragraphe mise_en_oeuvre_decision
      body.variables = { type: 'paragraph', bundle: 'mise_en_oeuvre_decision' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_mise_en_oeuvre_decision[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_mise_en_oeuvre_decision', this.p_mise_en_oeuvre_decision);
          
        })

      // paragraphe reception_application_decision
      body.variables = { type: 'paragraph', bundle: 'reception_application_decision' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_reception_application_decision[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_reception_application_decision', this.p_reception_application_decision);
          
        })

    },
    hideShowConcernement (id, state) {
      console.log(`disableConcernement id: ${id}`);
      this.concernements.forEach((c, i) => {
        if (c.id === id) {
          this.concernements[i].visible = this.concernementsByID[id].visible = state;  
        }
      })
    },
    openCloseConcernements (id) {
      console.log(`openCloseConcernements id: ${id}`);
      var state;
      this.concernements.forEach((c, i) => {
        state = id === c.id;
        this.concernements[i].opened = this.concernementsByID[c.id].opened = state;
        if (state) {
          this.opened_concernement = c;
        }
      });
    },
    resetConcernementOpened () {
      this.opened_concernement = null;
      this.openCloseConcernements();
    },
    setOpenedEntityId(id){
      this.opened_entite_id = id;
    }
  }
})