<script>

import { mapActions, mapState } from 'pinia'
import { ConcernementsStore } from '@stores/concernements'
import { UserStore } from '@/stores/user'
import { CommonStore } from '@/stores/common'

import REST from '@api/rest-axios'

import CartoucheLayout from '@components/layout/CartoucheLayout.vue';

import SvgIcon from '@jamescoyle/vue-icon';
import { mdiChevronRight } from '@mdi/js';
import { mdiChevronDown } from '@mdi/js';
import { mdiPencilPlus } from '@mdi/js';
import { mdiPencilPlusOutline } from '@mdi/js';
import { mdiRhombus } from '@mdi/js';
import { mdiRhombusOutline } from '@mdi/js';
import { mdiStickerPlusOutline } from '@mdi/js';


export default {
  props: ['cid'],
  data(){
    return {
      opened_besoin_id: null,
      chevronright_path: mdiChevronRight,
      chevrondown_path: mdiChevronDown,
      pencilplus_path: mdiPencilPlus,
      pencilplusoutline_path: mdiPencilPlusOutline,
      rhombus_path: mdiRhombus,
      rhombusoutline_path: mdiRhombusOutline,
      mdiStickerPlusOutline_path: mdiStickerPlusOutline,
      reloading_concernements: false,
    }
  },
  computed: {
    ...mapState(UserStore,['isloggedin', 'csrf_token']),
    ...mapState(ConcernementsStore,['opened_concernement',
                                    'ct_concernement',
                                    'ct_entite'
                                  ]),
    ...mapState(CommonStore,['hover_elmt'])
  },
  created () {
    console.log(`puissance d'agir content created, id: ${this.id}, opened_concernement:`,this.opened_concernement);
  },
  mounted() {
    
  },
  methods: {
    ...mapActions(CommonStore,['setHoverElmt']),
    ...mapActions(ConcernementsStore, ['reloadConcernementBesoins']),
    onClickBesoin(id){
      console.log("onClickBesoin", id);
      this.opened_besoin_id = id === this.opened_besoin_id ? null : id;
    },
    besoinClass(id){
      return this.opened_besoin_id === id ? "opened" : "";
    },
    onHoverItem(type, pid, bid, rid){
      console.log(`onHoverItem type:${type}, paper_id:${pid} bid:${bid}, rid:${rid}`);
      this.setHoverElmt({
        type: type,
        paper_id: pid,
        id: rid ? rid : bid,
        bid: rid ? bid : null,
        no_popup: true
      });
    },
    addBesoin(e){
      console.log('add besoin');
      this.reloading_concernements = true;
      // 1 create besoin node
      this.createBesoinNode()
        .then((besoin) => {
          console.log('createBesoinNode then node', besoin);
          // 2 record new besoin in concernement's field_besoin 
          this.recordConcernementBesoinField(besoin)
            .then((concernement) => {
              console.log('concernement', concernement);
              // reload the map item
              this.reloadConcernementBesoins(concernement.nid[0].value)
                .then(() => {
                  this.reloading_concernements = false;
                });
            })
        })
    },
    createBesoinNode(){
      return new Promise((resolve, reject) => {
        // 1 create entite node
        const params_node_besoin = {
          type: 'besoin',
          body: [{value:'Description à personaliser'}],
          field_confidentialite: [{value:'confidentialite_public'}]
        };
        
        const configs = {
          headers: {'X-CSRF-Token': this.csrf_token}
        };

        REST.post(`/node?_format=json`, params_node_besoin, configs)
          .then(({ data }) => {
            console.log('REST post new node besoin', data);
            resolve(data)
          })
          .catch(error => {
            console.warn(`Issue with post new node besoin`, error)
            reject(error)
          })
      })
    },
    recordConcernementBesoinField(new_besoin){
      return new Promise((resolve, reject) => {
        // 3 record concernement field_entite

        // get all the field_entite values, we don't want to ersae everything
        let besoins = [];
        this.opened_concernement.besoins.forEach((besoin) =>{
          besoins.push({
            target_id: besoin.id
          })
        })
        // add the new field value
        besoins.push({
          target_id: new_besoin.nid[0].value
        })
        console.log('besoins', besoins);
        
        const params_node = {
          type: 'concernement',
          nid: [{value: this.cid}],
          'field_besoin': besoins
        };
        
        const configs = {
          headers: {'X-CSRF-Token': this.csrf_token}
        };

        REST.patch(`/node/${this.cid}?_format=json`, params_node, configs)
          .then(({ data }) => {
            console.log('REST patch entite new field_entite', data)
            resolve(data)
          })
          .catch(error => {
            console.warn(`Issue with patch node entite field_entite`, error)
            reject(error)
          })
        // resolve('test')
      })
    },
  },
  components: {
    CartoucheLayout,
    SvgIcon
  }
}

</script>

<template>
  <CartoucheLayout :cid="cid">
    <!-- <template v-slot:header>
    </template> -->

    
    <template v-slot:main>

      <ul class="besoins">
        <li
          v-for="besoin in opened_concernement.besoins"
          :key="besoin.id"
          class="besoin"
          :id="besoin.id"
          :class="besoinClass(besoin.id)"
          @mouseover="onHoverItem('besoin', besoin.paper_id, besoin.id)"
        >
          <svg-icon
            type="mdi" 
            :path="besoin.id !== opened_besoin_id ? chevronright_path : chevrondown_path"
            class="open-btn"
            @click="onClickBesoin(besoin.id)"
            ></svg-icon>
          <header @click="onClickBesoin(besoin.id)">
            <label 
              :class="{ 'hover': hover_elmt 
                              && (hover_elmt.type === 'besoin' || hover_elmt.type === 'reponse') 
                              && (hover_elmt.id === besoin.id || hover_elmt.bid === besoin.id) }"
              >
              <svg-icon
                type="mdi" 
                :path="rhombus_path"
                 />
                Besoin de l'enqueteur
            </label>
            <h4 class="besoin-description" v-html="besoin.description"/>
          </header>
          <ul class="reponses">
            <li
              v-for="reponse in besoin.reponses"
              :key="reponse.id"
              class="reponse"
              :id="reponse.id"
              @mouseover.stop="onHoverItem('reponse', reponse.paper_id, besoin.id, reponse.id)"
            >
              <label 
              :class="{ 'hover': hover_elmt 
                              && hover_elmt.type === 'reponse' 
                              && hover_elmt.id === reponse.id }"
                >
                <svg-icon
                type="mdi" 
                :path="hover_elmt && hover_elmt.type === 'reponse' && hover_elmt.id === reponse.id ? rhombus_path : rhombusoutline_path"
                 />
                Ressource</label>
              <section v-if="reponse.qui">
                <label for="reponse-qui">Qui</label>
                <p name="reponse-qui" v-html="reponse.qui" />
              </section>
              <section v-if="reponse.quoi">
                <label for="reponse-quoi">Quoi</label>
                <p name="reponse-quoi" v-html="reponse.quoi" />
              </section>    
              <section v-if="reponse.ou">
                <label for="reponse-ou">Où</label>
                <p name="reponse-ou" v-html="reponse.ou" />
              </section>    
              <section v-if="reponse.avec">
                <label for="reponse-avec">Avec</label>
                <p name="reponse-avec" v-html="reponse.avec" />
              </section>    
            </li>
          </ul>
          <a 
              v-if="isloggedin"
              :href="'/api/node/add/reponse?besoin_id='+besoin.id" 
              target="_blank" 
              rel="noopener noreferrer"
              class="contribute-link mdi mdi-pencil-plus">
                <svg-icon type="mdi" :path="pencilplusoutline_path" /> contribuer à ce besoin
            </a>
        </li>
      </ul>
    </template>

    <template v-slot:footer>
    
      <template v-if="opened_concernement.can_update">
        <div v-if="!reloading_concernements" @click="addBesoin" class="add-besoin-btn">
          <span>Ajouter un besoin</span>
          <svg-icon type="mdi" :path="mdiStickerPlusOutline_path"/>
        </div>
        <div v-else class="add-besoin-btn">
          <div class="loading">Chargement</div>
        </div>
      </template>
    </template>

  </CartoucheLayout>
  
</template>