<script>

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

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

import ContentEditable from '@components/editable/ContentEditable.vue';

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

import { nextTick } from 'vue'

export default {
  props: {
    can_update: Boolean,
    files: Object,
    data: Object,
    label: String,
  },
  emits: ['updated'],
  data(){
    return {
      mdiTrashCanOutline_path: mdiTrashCanOutline,
      mdiFilePlusOutline_path: mdiFilePlusOutline,
    }
  },
  computed: {
    ...mapState(UserStore,['csrf_token']),
  },
  created () {
    console.log('ImageEditable created')
  },
  mounted () {

  },
  methods: {
    ...mapActions(ConcernementsStore, ['reloadConcernements']),
    addFile(e){
      console.log('addFile', this.$refs);
      this.$refs.file_input.click();
    },
    onInputNewfile(e){
      console.log('onFileInput', e);
      let file = e.target.files[0];
      console.log('onFileInput file', file);
      this.saveNewFile(file);
    },
    saveNewFile(file){
      const filename = file.name.normalize('NFD').replace(/[\u0300-\u036f]/g, "").replace(/[^a-zA-Z0-9_\-\.]/g, "_");  // Normalisation Unicode et suppression des accents
      console.log('filename', filename);
      
      const configs = {
        headers: {
          'X-CSRF-Token': this.csrf_token,
          'Content-Type': 'application/octet-stream',
          'Content-Disposition': `file; filename="${filename}"`,
        },
      };

      JSONAPI.post(`/${this.data.entitytype}/${this.data.bundle}/${this.data.uuid}/${this.data.field.field_name}`, file, configs)
        .then(({ data : { data } }) => {
          console.log('jsonapi post file', data)
          this.$emit('updated');
        })
        .catch(error => {
          console.warn('Issue with jsonapi post file', error)
          Promise.reject(error)
        })
    },
    onFocusOut(e){
      console.log('onfocusOut', e, this.$refs.file_list);
      this.buildFileListThenSaveList();
    },
    buildFileListThenSaveList(force_Save){
      console.log('buildLinkListThenSave files', this.files);
      // build links list
      let list = [];
      let tobesaved = false;
      for (let i = 0; i < this.$refs.file_list.children.length; i++) {
        const $li = this.$refs.file_list.children[i];
        console.log('$li', $li);
        if ($li.querySelector('input.description')) {
          let description = $li.querySelector('input.description').value;
          list.push({
            description: description,
            target_id: this.files[i].file.fid
          });
          tobesaved = (description !== this.files[i].description);
        }
      }
      if (!tobesaved) {
        tobesaved = this.files.length !== list.length;
      }

      if (tobesaved || force_Save) {
        this.saveList(list);
      }
    },
    saveList(list){
      console.log('saveList list', list);
      const params = {
        type: this.data.bundle,
        [this.data.field.field_name]: list
      };
      if (this.data.entitytype === 'node') {
        params.nid = [{"value":this.data.id}];
      } else {
        params.id = [{"value":this.data.id}];
      }
      // // we need additional values for image alt for example
      // // console.log('additional_values', this.data.field.additional_values);
      // if (this.data.field.additional_values) {
      //   for (const key in this.data.field.additional_values) {
      //     if (Object.hasOwnProperty.call(this.data.field.additional_values, key)) {
      //       params[this.data.field.field_name][0][key] = this.data.field.additional_values[key]
      //     }
      //   }
      // }
      
      const configs = {
        headers: {'X-CSRF-Token': this.csrf_token}
      };

      // url is not the same between nodes and others entities
      let url_base = `/${this.data.entitytype === 'node' ? '' : 'entity/'}${this.data.entitytype}`;
      // call the api
      REST.patch(`${url_base}/${this.data.id}?_format=json`, params, configs)
        .then(({ data }) => {
          console.log('user REST post node data', data)
          this.$emit('updated');
        })
        .catch(error => {
          console.warn(`Issue with patch ${this.data.entitytype} ${this.data.bundle}`, error)
          Promise.reject(error)
        })
    },
    async onDeleteFile(i){
      console.log(`onDeleteLink ${i}`, this.$refs.file_list.children[i]);
      // this.links_nb = this.$refs.links_list.children.length;
      // this.$refs.links_list.children[i].remove();
      this.files.splice(i,1);
      await nextTick();
      this.buildFileListThenSaveList(true);
    },
    onUpdated(){
      this.$emit('updated');
    },
    fileMime(mime){
      return mime.replace('application/', '');
    },
    docLabel(doc){
      return doc.description ? doc.description : doc.file.filename;
    }
  },
  components: {
    SvgIcon,
    ContentEditable
  }
}
</script>

<template>
  <label>{{ label }}</label>
  <ul ref="file_list" class="editable-files" :class="{'can-update': can_update}">
    <li v-for="(doc,d) in files" :key="d" class="file-editable">
      <template v-if="!can_update">
        <a
          :href="doc.file.url"
          target="_blank"
        >
          {{ docLabel(doc) }} [{{ fileMime(doc.file.filemime) }}]
        </a>  
      </template>
      <template v-else>
        <input type="text" class="description" :value="doc.description" placeholder="Description du fichier" @focusout="onFocusOut" />
        <!-- <input type="text" class="url" :value="link.url" @focusout="onFocusOut" placeholder="Url du lien" /> -->
        <div class="filename">{{ doc.file.filename }}</div>
        <div @click="onDeleteFile(d)" class="delete-btn">
          <svg-icon type="mdi" :path="mdiTrashCanOutline_path" />
        </div>
      </template>
    </li>
    <li v-if="can_update">
      <div @click="addFile" class="file-btn">
        <svg-icon type="mdi" :path="mdiFilePlusOutline_path"/>
      </div>
      <input ref="file_input" type="file" accept="application/txt, application/pdf, application/doc, application/docx, application/obs, application/xls"   @input="onInputNewfile"/>
    </li>
  </ul>
</template>