<template>
	<div>

		<!-- hover over view -->
		<div v-if="fullTagEdit" class="full-tag-area fade-in-fwd">

			<div class="ui grid">

				<div class="sixteen wide column">
					<h2><i class="green tags icon"></i>Edit Tags</h2>
				</div>

				<div class="sixteen wide column">
					<h3>All Tags</h3>
					<div v-if="allTags.length > 0">
						<div class="ui icon large label" v-for="tag in allTags" :class="{ 'green':isTagOnNote(tag.id) }">
							 {{ ucWords(tag.text) }}
						</div>
					</div>
				</div>

				<div class="sixteen wide column">
					<h3>Tags on Note</h3>
					<div v-if="allTags.length > 0 && noteTagIds.length > 0">
						<div class="ui icon large label" v-for="tag in noteTagIds">
							 {{ getTagTextById(tag['tagId']) }} <i class="delete icon" v-on:click="removeTag(tag['entryId'])"></i>
						</div>
					</div>
				</div>

			</div>


			<!-- tag input and suggestion popup -->
			<div class="ui form">
				<input 
					placeholder="Tag name. Press (Up) to select suggestion. Press (Enter) to submit."
					v-model="newTagInput"
					v-on:keydown="tagInput"
					v-on:keyup="onKeyup"
					v-on:blur="onBlur"
					v-on:focus="onFocus"
				/>
				<div class="suggestion-box" v-if="suggestions.length > 0">
					<div class="suggestion-item" v-for="(item, index) in suggestions" :class="{ 'active':(index == selection) }" v-on:click="onClickTag(index)">
						{{ucWords(item.text)}} <span class="suggestion-tip" v-if="index == selection">Press Enter to add</span>
					</div>
				</div>
			</div>

		</div>
	</div>
</template>

<script>
	
	import axios from 'axios';

	export default {
	name: 'NoteTagEdit',
		props: [ 'noteId' ],
		data () {
			return {
				tags: [],
				newTagInput: '',
				typeDebounce: null,

				allTags: [],
				noteTagIds: [],
				suggestions: [],
				selection: 0,
				fullTagEdit: true,
				loaded: false,
			}
		},
		beforeMount(){

		},
		mounted() {
			this.getTags()
		},
		methods: {
			getTags(){
				//Get Note Tags -> /api/tags/get
				axios.post('/api/tag/get', {'noteId': this.noteId})
				.then( ({data}) => {

					this.loaded = true

					this.allTags = data.allTags
					this.noteTagIds = data.noteTagIds
				})
			},
			isTagOnNote(id){
				for (let i = 0; i < this.noteTagIds.length; i++) {
					const current = this.noteTagIds[i]
					if(current && current['tagId'] == id){
						return true
					}
				}
			},
			getTagTextById(id){
				let tag = this.getTagById(id)
				if(tag && tag.text){
					return this.ucWords( tag.text )
				}
			},
			getTagById(id){
				for (let i = 0; i < this.allTags.length; i++) {
					const current = this.allTags[i]
					if(current && current['id'] == id){
						return current
					}
				}
			},
			tagInput(event){
				let vm = this

				//Cancel any of the following key events
				const code = event.keyCode
				if([38, 40, 13, 9].includes(code)){
					event.preventDefault()
				}
				
				//Up - 38 - Go Up suggestion
				if(code == 40){
					this.selection ++
					if(this.selection >= this.suggestions.length){
						this.selection = -1 //No selection made
					}
					return
				}
				//Down - 40 - Go Down Suggestion
				if(code == 38){
					this.selection --
					if(this.selection < -1){
						this.selection = this.suggestions.length -1 //No selection made
					}
					return;
				}
				
				//Enter - 13 - Execute addTag() function
				if(code == 13){
					//If an item from list is selected, make that the text
					if(this.selection > -1){
						this.newTagInput = this.suggestions[vm.selection].text
					}
					this.addTag()

					return
				}

				//Tab - 9 - Fill space with suggestion

				//Anything else, perform search
				clearTimeout(this.typeDebounce)
				this.typeDebounce = setTimeout( () => {
					if(event.target.value.length > 0){

						const postData = {
							'tagText':vm.newTagInput,
							'noteId':vm.noteId
						}

						axios.post('/api/tag/suggest', postData)
						.then(response => {

							vm.suggestions = response.data
							vm.selection = -1 //Nothing selected
						})
					}
				}, 300)
			},
			onClickTag(index){
				this.newTagInput = this.suggestions[index].text
				this.addTag()
			},
			addTag(){

				//Don't add blank or empty tags
				if(this.newTagInput == ''){
					return
				}

				let postData = {
					'tagText':this.newTagInput.trim(),
					'noteId':this.noteId
				}
				let vm = this
				axios.post('/api/tag/addtonote', postData)
				.then(response => {
					vm.newTagInput = ''
					vm.clearSuggestions()
					vm.getTags()
					//Trigger focus event to reload tag suggestions
					vm.onFocus()
				})
			},
			onFocus(){
				return
				//Show suggested tags
				let vm = this
				let postData = {
					'noteId':this.noteId
				}
				axios.post('/api/tag/latest', postData)
				.then(response => {

					vm.suggestions = response.data
					vm.selection = -1 //Nothing selected
				})
			},
			onKeyup(){

				const code = event.keyCode

				//Backspace - clear old suggestions, load latest suggestions
				if(code == 8 && this.newTagInput.length == 0){
					//Fetch suggestions
					this.onFocus()
				}
			},
			onBlur(){
				let vm = this
				setTimeout(i => {
					vm.clearSuggestions()
				}, 200)
			},
			removeTag(tagId){

				let postData = {
					'tagId':tagId,
					'noteId':this.noteId
				}

				axios.post('/api/tag/removefromnote', postData)
				.then(response => {
					this.getTags()
				})
			},
			clearSuggestions(){
				this.suggestions = []
				this.selection = -1 //No selections
			},
			ucWords(str){
				return (str + '')
				.replace(/^(.)|\s+(.)/g, function ($1) {
					return $1.toUpperCase()
				})
			}
		}
	}
</script>
<style type="text/css" scoped>

	/* note tag edit area */
	.full-tag-area {
		
		color: var(--text_color);
		background-color: var(--background_color);
		/*padding: 15px;*/
		/*border: 1px solid;*/
		border-color: var(--border_color);
	}
	.full-tag-area .delete-tag-display {
		/*margin-top: 15px;*/
	}
	.full-tag-area .ui.label {
		margin-bottom: 5px;
	}
	.simple-tag-display {
		width: calc(100% - 0px);
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-height: 35px;
		color: var(--text_color);
		cursor: pointer;
	}

	/* tag suggestion box styles */
	.suggestion-box {
	    position: absolute;
	    bottom: 38px;
	    width: 300px;
	    box-shadow: 0px 0px 5px 2px rgba(140,140,140,1);
	}
	.suggestion-item {
		width: 100%;
		height: 40px;
		padding: 10px 15px;
		cursor: pointer;
		background-color: var(--background_color);
		color: var(--text_color);
	}
	.suggestion-item.active {
		background: green;
		color: white;
	}
	.suggestion-item + .suggestion-item {
		border-top: 1px solid #DDD;
	}
	.suggestion-tip {
		float: right;
	}
</style>