<template src='./template.html'></template>
<style scoped src='./style.css'></style>

<script>
	import typeahead from 'vue-typeahead'
	import Taglist from '../taglist/Taglist.vue'

	var autoCompletePath = "http://lookup.dbpedia.org/api/search/PrefixSearch?MaxHits=5";
	var wikipediaPath = "http://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],
		components: { 'taglist' : Taglist },
		
		props: ['tags', 'read-only'],

		mounted() {
			this.taglist = this.$refs.taglist;
			this.taglist.readOnly = this.readOnly;
			this.setTags(this.tags);
		},

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

			}
		},

		methods: {
			
			setTags(tags, reset) {
				tags = Array.isArray(tags) ? tags : []; 
				reset = (typeof reset === "boolean") ? reset : false;
				if (reset) {
					this.taglist.reset();
				}
				this.taglist.setTags(tags);
			},

      		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 = 1;
      				tagItem.relevancy = 1;
      				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;
      		},

      		addTag () {
      			if (this.hasItems) { return false; }
      			var tag = {tag_label: this.query, accuracy: 1, relevancy: 1};
      			this.$refs.taglist.addTag(tag);
      			this.reset();
      		},

			onHit (selected) {
				this.$refs.taglist.addTag(selected);
				this.reset();
			}
		}

	}

</script> 