<script>

import REST from '@api/rest-axios'
import JSONAPI from '@api/json-axios'

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

import Source from '@components/contents/Source.vue';
import ContentEditable from '@components/editable/ContentEditable.vue';
import CheckboxEditable from '@components/editable/CheckboxEditable.vue';
import ImageEditable from '@components/editable/ImageEditable.vue';

import SvgIcon from '@jamescoyle/vue-icon';
import { mdiTextBoxPlusOutline } from '@mdi/js';

export default {
  props: ['concernement', 'entite', 'eid'],
  emits: ['reloadEntite'],
  data() {
    return {
      mdiTextBoxPlusOutline_path: mdiTextBoxPlusOutline,
    }
  },
  computed: {
    ...mapState(ConcernementsStore,['opened_concernement',
                                    'ct_concernement',
                                    'ct_entite']),
    ...mapState(UserStore,['csrf_token']),
    field_menace_maintien_label (){
      let str;
      if (this.concernement.entites_byid[this.eid].menacemaintien < 0) {
        str = this.ct_entite.field_menace_maintien.description.replace('/maintient', '')
      } else {
        str = this.ct_entite.field_menace_maintien.description.replace('menace/', '')
      }
      return str;
    },
  },
  methods: {
    reloadEntite(){
      this.$emit('reloadEntite');
    },
    addSource(){
      console.log('add source');
      const params_parag = {
        type: [{target_id: 'source'}],
        parent_type:{value: 'node'},
        parent_id:{value: this.entite.id},
        parent_field_name:{value: 'field_sources'}
      };
      
      const configs = {
        headers: {'X-CSRF-Token': this.csrf_token}
      };

      // call the api
      // https://www.drupal.org/project/paragraphs/issues/3012600
      REST.post(`/entity/paragraph?_format=json`, params_parag, configs)
        .then(({ data }) => {
          console.log('REST post new source parag', data);
          
            const params_node = {
              type: 'entite',
              nid: [{value: this.entite.id}],
              'field_sources': [{
                target_id: data.id[0].value,
                target_revision_id: data.revision_id[0].value
              }]
            };
            

            // call the api
            REST.patch(`/node/${this.entite.id}?_format=json`, params_node, configs)
              .then(({ data }) => {
                console.log('REST patch entite new field_sources', data)
                this.reloadEntite();
              })
              .catch(error => {
                console.warn(`Issue with patch node entite field_sources`, error)
                Promise.reject(error)
              })
    
    
        })
        .catch(error => {
          console.warn(`Issue with post new paragraph source`, error)
          Promise.reject(error)
        })

    
    }
  },
  components: {
    Source,
    ContentEditable,
    CheckboxEditable,
    ImageEditable,
    SvgIcon
  }
}
</script>

<template>
  <section class="entite">
    <section v-if="entite.image.length || entite.can_update" class="image">
      <ImageEditable 
        :can_update="entite.can_update"
        :image="entite.image[0]"
        :data="{
          entitytype: 'node',
          bundle: 'entite',
          id: this.entite.id,
          uuid: this.entite.uuid,
          field: 'field_image'
        }"
        v-on:updated="reloadEntite" />

    </section>
    <section v-if="entite.action || entite.can_update" class="action">
        <label v-if="ct_entite">{{ ct_entite.field_action.description }}</label>
        <!-- <p>{{ entite.action }}</p> -->
        <ContentEditable 
          tag="p"
          :value="entite.action"
          :contenteditable="entite.can_update"
          :data="{
            entitytype: 'node',
            bundle: 'entite',
            id: this.entite.id,
            field: {field_name: 'field_action', value:'value'}
          }"
          v-on:updated="reloadEntite" />
          
    </section>
    <section v-if="entite.menacemaintien || entite.can_update" class="menace-maintien">
        <label v-if="ct_entite">{{ field_menace_maintien_label }}</label>
        <!-- <p>{{ entite.menacemaintien }}</p> -->
        <ContentEditable 
          tag="p"
          :value="entite.menacemaintien"
          :contenteditable="entite.can_update"
          :data="{
            entitytype: 'node',
            bundle: 'entite',
            id: this.entite.id,
            field: {field_name: 'field_menace_maintien', value:'value'}
          }"
          v-on:updated="reloadEntite" />
        
    </section>
    <!-- SOURCES (experiences vecues) -->
    <section
      v-if="entite.sources.length" 
      class="sources multiple">
      <!-- <h5>Experience(s) Vécue(s)</h5> -->
      <Source 
        v-for="(source, index) in entite.sources"
        :key="index" 
        :concernement="concernement"
        :entite="entite"
        :eid="eid"
        :source="source"
        v-on:reloadEntite="reloadEntite" />
    </section>
    <section 
      v-else-if="entite.can_update"
      class="sources add">
      <div @click="addSource" class="add-source-btn">
        <span>Ajouter une experience vécue</span>
        <svg-icon type="mdi" :path="mdiTextBoxPlusOutline_path"/>
      </div>
    </section>
  </section>
</template>

<style lang="css">
  section.action p,
  section.menace-maintien p {
    white-space: pre-wrap;
  }
</style>