import Vue from 'vue/dist/vue'
import EventBus from '../util/EventBus';
import EventTypes from '../util/EventTypes';

Vue.component('media-listing', {
    props: {
        context: {
            type: Object,
            default() {
                return {}
            }
        },
        items: {
            type: Array,
            default() {
                return []
            }
        },
    },
    data: function () {
        return {
            isDragging: false,
        };
    },
    methods: {
        getMediaKey: function (item) {
            return item.type + '#' + item.media.id;
        },
        resetSearch: function (){
            EventBus.$emit(EventTypes.LIBRARY_SEARCH, {
                searchTerm: '',
            });
        }
    },
    mounted() {
        console.log('Media listing mounted');

        this.$nextTick(() => {
            if (this.$refs.dropZoneRef) {
                this.$refs.dropZoneRef.addEventListener("dragover", () => {
                    this.isDragging = true;
                    if (this.isDragging) {
                        EventBus.$emit(EventTypes.LIBRARY_UPLOAD_PANE, true);
                    }
                });
                this.$refs.dropZoneRef.addEventListener("dragleave", () => {
                    this.isDragging = false;
                });
            }
        });
    },
    template: `
      <div class="library-listing" ref="dropZoneRef">
        <div class="container">
          <div class="row">
            <div v-if="context.items?.length === 0"
                 class="fake-media-item col-6"
            >
              <div class="inner-wrap">
                <p>Aucun résultats.</p>
                <button v-if="this.context?.searchTerm?.length > 0"
                        class="btn btn-secondary"
                        @click="resetSearch"
                >Vider la recherche</button>
              </div>
            </div>
            <media-item
                v-else
                v-for="item in context.items"
                v-bind:key="getMediaKey(item)"
                v-bind:id="item.media.id"
                v-bind:media="item.media"
                v-bind:type="item.type"
                v-bind:mediaUrl="item.mediaUrl"
                v-bind:sizeReadable="item.sizeReadable"
            ></media-item>
          </div>
        </div>
      </div>
    `
});