<template>
    <div>
        <input type="text"
            class="form-control input-sm"
            v-bind:disabled="readonly"
            v-bind:placeholder="placeholder"
            autocomplete="off"
            v-model="query"
            @keydown.down="down"
            @keydown.up="up"
            @keydown.enter="hit($event)"
            @keydown.esc="reset"
            @blur="reset"
            @input="update" />
        <ul v-show="hasItems">
            <li v-for="(item, index) in items" :class="activeClass(index)" @mousedown="hit" @mousemove="setActive(index)">
                <span v-text="item.tag_label"></span>
            </li>
        </ul>
    </div>
</template>

<style scoped src="./typeahead.css"></style>

<script>

    import typeahead from 'vue-typeahead'

    var autoCompletePath = "https://lookup.dbpedia.org/api/search/PrefixSearch?MaxHits=5";
    var wikipediaPath = "https://fr.wikipedia.org/w/api.php"
    var parentsMethods = {
        reset: typeahead.methods.reset
    };


    var get = function (url, data) {
        var dfd = jQuery.Deferred();
        var promise = jQuery.getJSON(url, data).done( function (response) {
            var envelope = {};
            envelope.data = response;
            dfd.resolve(envelope);
        }).fail(dfd.reject);
        return dfd.promise();
    }

    export default {
        mixins: [typeahead],

        props: {
            placeholder: String,
            readonly: {
                type: Boolean,
                default: false
            }
        },

        data() {
            return {
                src: autoCompletePath,
                limit: 7,
                minChars: 2,
                showAddButton: false,
                datasource: "wikipedia",
                selectedTags: "[]",
                items: [],
                queryParamName: "QueryString",
            }
        },

        methods: {

            checkQuery () {
                if (this.query.length === 0) {
                    this.reset();
                }
            },

            fetch() {
                if (this.datasource === "wikipedia") {
                    return this.fetchWikiPedia();
                }

                else {
                    var request = {};
                    request[this.queryParamName] = this.query;
                    return get(this.src, query);
                }
            },

            fetchWikiPedia () {
                this.src = wikipediaPath;
                var self = this;
                var request = {
                    'action': 'opensearch',
                    'format': 'json',
                    'search': this.query
                };

                /* make request */
                var dfd = jQuery.Deferred();
                jQuery.ajax({
                    url: this.src,
                    data: request,
                    dataType: "jsonp",
                    success: function (response) {
                        var envelope = {};
                        envelope.data = response;
                        dfd.resolve(envelope);
                    }
                });
                return dfd.promise();
            },

            reset () {
                this.showAddButton = false;
                parentsMethods.reset.call(this);
            },

            prepareWikipediaResponse (data) {
                var results = [];
                if (data.length !== 4) { return results; }
                var labelsList = data[1];
                var urlsList = data[3];

                if (labelsList.length !== urlsList.length) {
                    return;
                }

                labelsList.map(function(item, index) {
                    var tagItem = {};
                    tagItem.tag_label = item;
                    var link = urlsList[index];
                    link = link.replace("https://fr.wikipedia.org/wiki/", "http://fr.dbpedia.org/resource/");
                    tagItem.tag_link = decodeURI(link);
                    tagItem.accuracy = null;
                    tagItem.relevancy = null;
                    results.push(tagItem);
                });

                return results;
            },

            prepareResponseData (data) {
                var responseData = (typeof data === 'string') ? JSON.parse(data): data;

                if(this.datasource === "wikipedia") {
                    responseData = this.prepareWikipediaResponse(responseData);
                }

                if (Array.isArray(responseData) && !responseData.length) {
                    this.showAddButton = true;
                }
                return responseData;
            },

            onHit (selected) {
                this.$emit('selected', selected);
                this.reset();
            }
        }

    }

</script>
