<script>

import Typeahead from '../typeahead/Typeahead.vue'
import DiffViewer from '../diffviewer/diffviewer.vue'

export default {

	data () {
		return {}
	},
	
	components: {
		Typeahead: Typeahead,
		'diffviewer': DiffViewer
	},

	mounted () {

		this.targetKeyMap = {
			title: "proposal-title", 
			desc: "proposal-description",
			frag: "proposal-fragment"
		};

		this.targetFieldTypeMap = {
			title: "input", 
			desc: "input",
			frag: "frag"
		};

		this.originalValues = {
			title: "",
			desc: "",
			frag: ""
		}

	},

	methods: {

		pickProposition: function (event, sourceId, targetKey) {
			var value = "";
			var source = document.getElementById(sourceId);
			var targetField = this.$refs[this.targetKeyMap[targetKey]];
			var targetType = this.targetFieldTypeMap[targetKey];
			if (!targetType) { throw new Error("A target type must be provided..."); }
			
			if (targetType === "input") {
				value = targetField.value; 
				targetField.value = source.value;
			}

			 if (targetType === "frag") {
			 	value = targetField.getAttribute("d");
			 	var sourceValue = source.getAttribute("d");
			 	var targetPathType = targetField.getAttribute("data-path-type");
			 	targetField.setAttribute("d", sourceValue);
			 	
			 	var pathType = source.getAttribute("data-path-type");
			 	pathType = pathType || "FREE";
			 	var fragmentField = this.$refs["fragment-field"];
			 	fragmentField.value = sourceValue + ";" + pathType;
			 }

			 this.preserveOriginalValue(targetKey, value);
		},

		pickTag: function (event, refTag) {
			var source = this.$refs[refTag];
			var target = this.$refs['proposal-tags'];
			this.preserveOriginalValue('proposal-tags', target.tags);
			target.setTags(source.tags, true);
		},

		preserveOriginalValue: function (key, value) {
			if (!this.originalValues[key]) {
				this.originalValues[key] = value;
			}
		},

		showDiffviewer: function (refId, sourceId, targetKey) {

			var sourceField = document.getElementById(sourceId);
			var targetField = this.$refs[this.targetKeyMap[targetKey]];
			var targetType = this.targetFieldTypeMap[targetKey];
			var diffViewer = this.$refs[refId];
			
			if (!diffViewer) { throw new Error("The DiffViewer can't be found for " + targetKey); }

			if (targetType === "input") {
				diffViewer.showTextDiff(sourceField.value, targetField.value);
			}

			if (targetKey === "tag") {
				var source = this.$refs[sourceId];
				var target = this.$refs['proposal-tags'];
				if ((source.tags.length !== 0) && (target.tags.length !== 0)) {
					diffViewer.showTagDiff(source.tags, target.tags);
				}
			}
			/* frag */
			if ( targetKey === "frag") {
				
				var originalPath = targetField.getAttribute("d");
				var modifiedPath = sourceField.getAttribute("d");
				diffViewer.showFragmentDiff(originalPath, modifiedPath);
			}

			diffViewer.show();
		},


		hightlightSource: function (source) {
			source.className += "highlight";
		},

		save: function () {
			alert("this is it ... ");
		}
	}
}

</script>