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

Vue.component('library-search', {
    props: {
        context: {
            type: Object,
            default() {
                return {}
            }
        },
        // use context.searchTerm proxy to be able to clear from another comp
        inputVal: '',
    },
    data: function () {
        return {
            innerInputVal: '',
            previousVal: '',
            debounce: null,
            debounceTime: 300,
        };
    },
    methods: {
        debouncedChange: function (e) {
            EventBus.$emit(EventTypes.LIBRARY_SEARCH, {
                searchTerm: this.innerInputVal,
            });

            this.previousVal = this.innerInputVal;
        },
        change: function (event) {
            if (this.previousVal === event.target.value) {
                return;
            }
            this.previousVal = event.target.value;
            event.preventDefault();

            // debounce to grab full word
            if (this.debounce) {
                clearTimeout(this.debounce);
            }
            this.debounce = setTimeout(this.debouncedChange, this.debounceTime)

            return false;
        },
    },
    watch: {
        context: function (newVal, oldVal) {
            this.innerInputVal = newVal.searchTerm;
        }
    },

    mounted() {
    },
    template: `
      <div class="library-search">
        <div class="form-group">
          <input type="search"
                 class="form-control"
                 placeholder="Recherche..."
                 v-model="innerInputVal"
                 @input="change"
          >
        </div>
      </div>
    `
});