<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 { mdiMovieOpenPlusOutline } from '@mdi/js';


export default {
  props: {
    can_update: Boolean,
    video: Object,
    data: Object
  },
  emits: ['updated'],
  data(){
    return {
      mdiTrashCanOutline_path: mdiTrashCanOutline,
      mdiMovieOpenPlusOutline_path: mdiMovieOpenPlusOutline,
      plyr_options: {
        controls: ['play', 'progress', 'current-time', 'mute', 'volume']
      }
    }
  },
  computed: {
    ...mapState(UserStore,['csrf_token']),
  },
  created () {
    console.log('VideoEditable created');
  },
  mounted () {

  },
  methods: {
    ...mapActions(ConcernementsStore, ['reloadConcernements']),
    // addImage(e){
    //   console.log('addImage', this.$refs);
    //   this.$refs.image_input.click();
    // },
    onSaveVideoLink(e){
      console.log('onSaveVideoLink', e);
      let url = this.$refs.video_link_input.innerText;
      console.log('onSaveVideoLink url', url);
      this.save(url);
    },
    save(content){
      // console.log('save csrf_token', this.csrf_token);
      const params = {
        type: this.data.bundle,
        [this.data.field.field_name]: [{[this.data.field.value]: content}]
      };
      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}
      };

      let url_base = `/${this.data.entitytype === 'node' ? '' : 'entity/'}${this.data.entitytype}`;
      REST.patch(`${url_base}/${this.data.id}?_format=json`, params, configs)
        .then(({ data }) => {
          console.log('user REST post node data', data)
          // TODO if success update the data in pinia 
          // this.reloadConcernements();
          this.$emit('updated');
        })
        .catch(error => {
          console.warn(`Issue with patch ${this.data.entitytype} ${this.data.bundle}`, error)
          Promise.reject(error)
        })
    },
    onDeleteVideo(e){
      console.log('onDeleteVideo', e);

      const params = {
        type: this.data.bundle,
        // nid: [{"value":this.data.id}],
        [this.data.field.field_name]: {[this.data.field.value]: null}
      };
      if (this.data.entitytype === 'node') {
        params.nid = [{"value":this.data.id}];
      } else {
        params.id = [{"value":this.data.id}];
      }

      const configs = {
        headers: {'X-CSRF-Token': this.csrf_token}
      };
      
      let url_base = `/${this.data.entitytype === 'node' ? '' : 'entity/'}${this.data.entitytype}`;
      REST.patch(`${url_base}/${this.data.id}?_format=json`, params, configs)
        .then(({ data }) => {
          console.log(`user REST patch node ${this.data.bundle} ${this.data.field}`, data)
          this.$emit('updated');
        })
        .catch(error => {
          console.warn(`Issue with patch node ${this.data.bundle} ${this.data.field}`, error)
          Promise.reject(error)
        })

      // 405 JSONAPI operation not allowed, don't know why
      
      // const configs = {
      //   headers: {
      //     'X-CSRF-Token': this.csrf_token,
      //     'Content-Type': 'application/octet-stream',
      //     'Content-Disposition': `file; filename=""`,
      //   },
      // };

      // JSONAPI.delete(`/${this.data.entitytype}/${this.data.bundle}/${this.data.uuid}/${this.data.field}`, {}, configs)
      //   .then(({ data : { data } }) => {
      //     console.log('jsonapi delete image', data)
      //     this.$emit('updated');
      //   })
      //   .catch(error => {
      //     console.warn('Issue with jsonapi post image', error)
      //     Promise.reject(error)
      //   })
      // console.log('save csrf_token', this.csrf_token);

    }
  },
  components: {
    SvgIcon,
    ContentEditable
  }
}
</script>

<template>
  <div class="editable-video">
    <!-- with video -->
    <template v-if="video">
      <!-- v-for="(video,v) in source.videos"
      :key="v" -->
      <vue-plyr
          >
            <div class="plyr__video-embed">
              <!-- TODO fix vimeo embed url -->
              <iframe 
                :src="video.url"
                allowfullscreen
              ></iframe>
            </div>
        </vue-plyr>
      <div v-if="can_update" @click="onDeleteVideo" class="delete-btn">
        <svg-icon type="mdi" :path="mdiTrashCanOutline_path" />
      </div>
    </template>
    <!-- with out video -->
    <template v-else-if="can_update">
      <!-- <input ref="videolink_input" type="text" @input="onInput"> -->
      <div class="editable-wrapper">
        <div 
          ref="video_link_input"
          :contenteditable="can_update"
          :spellcheck="spellcheck"
          data-placeholder="coller un lien de video" />
          <!-- @focusout="onVideoInputFocusOut" -->
        <svg-icon class="video-btn" type="mdi" :path="mdiMovieOpenPlusOutline_path" @click="onSaveVideoLink"/>
      </div>
    </template>
    
  </div>
</template>

<style scoped>
  .editable-wrapper{
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 0.5em;
  }
  [contenteditable] {
    flex: auto 1 0;
    /* display: inline-block; */
    /* padding:12px;  */
    /* background:red; */
    /* min-height: 1em;  */
  }
  [data-placeholder]:empty:before{
    content: attr(data-placeholder);
    color: #888;
    font-style: italic;
  }
  svg{
    /* display: inline-block; */
    flex: auto 0 0;
  }
</style>