<template>
    <div>
        <input type="text"
            class="form-control input-sm"
            v-bind:disabled="readonly"
            v-bind:placeholder="placeholder"
            autocomplete="off"
            v-model="query"
            @keypress.enter="preventSubmit"
            @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 class="tag-label" v-text="item.tag_label"></span>
                <span  class="pull-right text-muted" v-if="!item.tag_link.startsWith('http')">créer</span>
            </li>
        </ul>
    </div>
</template>

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

<script>

    import typeahead from 'vue-typeahead'
    import _ from 'lodash'

    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,
                selectFirst: true,
                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 () {
                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 = 0;
                    tagItem.relevancy = 0;
                    results.push(tagItem);
                });

                return results;
            },

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

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

                var exactMatch = _.find(responseData, (tag) => tag.tag_label === _.upperFirst(this.query));
                if (!exactMatch) {
                    if (Array.isArray(responseData)) {
                        responseData.unshift({
                            tag_label: this.query,
                            tag_link: this.query,
                            accuracy: 0,
                            relevancy: 0
                        });
                    }
                }

                return responseData;
            },

            onHit (selected) {
                if (!selected) { return; }
                this.$emit('selected', selected);
                this.reset();
            },
            preventSubmit(e) {
                e.preventDefault();
                e.stopPropagation();
            }
        }

    }

</script>
