<template>
	<div>
		

		<div class="ui grid">
			<!-- search menu  -->
			<div class="ui row">
				<div @click="createNote" class="ui green button">
								<i class="plus icon"></i>
								New Note
							</div>
							<input v-model="searchTerm" @keyup="searchKeyUp" @:keyup.enter="search" placeholder="Search Notes" />
							<div class="ui button" @click="reset">Reset</div>
			</div>
			<div class="ui row">
				<div class="ui two wide column">
					<div class="ui clickable basic fluid large label" v-for="tag in commonTags" @click="toggleTagFilter(tag.id)" 
						:class="{ 'green':(searchTags.includes(tag.id)) }">
						{{ucWords(tag.text)}} <div class="detail">{{tag.usages}}</div>
					</div>
				</div>
				<div class="ui fourteen wide column">
					<div v-if="notes !== null">
						<div class="ui vertical segment clickable" v-for="note in notes" v-on:click="openNote(note.id)" v-html="note.text">
						</div>
					</div>
				</div>
			</div>
		</div>

	</div>
</template>

<script>
	
	import axios from 'axios';

	export default {
	name: 'SearchBar',
		data () {
			return {
				initComponent: true,
				commonTags: [],
				searchTerm: '',
				searchTags: [],
				notes: null,
				searchDebounce: null
			}
		},
		beforeMount(){

		},
		mounted() {
			this.search()
		},
		methods: {
			toggleTagFilter(tagId){

				if(this.searchTags.includes(tagId)){
					this.searchTags.splice( this.searchTags.indexOf(tagId) , 1);
				} else {
					this.searchTags.push(tagId)
				}

				this.search()
			},
			search(){
				let postData = {
					searchQuery: this.searchTerm,
					searchTags: this.searchTags
				}
				//Perform search
				let vm = this
				axios.post('/api/notes/search', postData).
				then(response => {
					console.log('Notes and Tags')
					console.log(response.data)

					vm.commonTags = response.data.tags
					vm.notes = response.data.notes
				})
			},
			searchKeyUp(){
				let vm = this
				clearTimeout(vm.searchDebounce)
				vm.searchDebounce = setTimeout(() => {
					vm.search()
				}, 300)
			},
			createNote(event){
				const title = ''
				let vm = this

				axios.post('/api/notes/create', {title})
				.then(response => {

					if(response.data && response.data.id){
						vm.openNote(response.data.id)
					}
				})
			},
			openNote(noteId){
				//Emit open note event
				this.$bus.$emit('open_note', noteId)
			},
			ucWords(str){
				return (str + '')
				.replace(/^(.)|\s+(.)/g, function ($1) {
					return $1.toUpperCase()
				})
			},
			reset(){
				this.searchTerm = ''
				this.searchTags = []
				this.search()
			}
		}
	}
</script>
<style type="text/css" scoped>
	.detail {
		float: right;
	}
</style>