<template src='./template.html'></template>
<script>

import { generateId } from '../utils'

export default {
	data () {
		return {
			tags: [],
			readOnly: false
		}
	},

	methods: {
		removeTag: function (index) {
			this.tags.splice(index, 1);
			this.normalizeSelectedTags();
		},

		reset: function () {
			this.tags = [];
			this.normalizeSelectedTags();
		},

		/* check tag already exists */
		tagAlreadyExists (tag) {
			var result = false;
			var found = this.tags.find(function (userTag) {

				if (!userTag.tag_link) {

					if (userTag.tag_label === tag.tag_label) {
						return true;
					}

				} else {
					if (userTag.tag_link === tag.tag_link) {
						return true;
					}
				}
			});
			if (found) {
				var tagNode = this.$refs[found.id][0];
				tagNode.style.border = "1px solid red";
				setTimeout(function () {
					tagNode.style.border = "";
				}, 1000);
				result = true;
			}
			return result;
		},

		setTags (tagArrays){

			if (!Array.isArray(tagArrays)) { new Error('setTags expects an array!'); }
			var self = this;
			tagArrays.map(function (tag) {
				self.addTag(tag);
			});
		},

		addTag (tag) {

			if (this.tagAlreadyExists(tag)) { return false; }

			if (!tag || !tag.hasOwnProperty('tag_label')) { return; }

			if (!tag.id) {
				tag.id = generateId('tag_');
			}

			this.tags.push(tag);
			this.normalizeSelectedTags();
		},

		normalizeSelectedTags () {
			var result = [];

			this.tags.map(function (tag) {
				var tagItem = {};
				tagItem.tag_input = (typeof tag.tag_link === "string" && tag.tag_link.length) ? tag.tag_link: tag.tag_label;
				tagItem.accuracy = tag.accuracy;
				tagItem.relevancy = tag.relevancy;
				result.push(tagItem);
			});
			this.$parent.$data.selectedTags = JSON.stringify(result);
		},

		updateAccuracy: function (event, tag) {
			tag.accuracy = event.target.value;
			this.normalizeSelectedTags();

		},

		updatePertinence: function (event, tag) {
			tag.relevancy = event.target.value;
			this.normalizeSelectedTags();
		}
	}
}

</script>
