<template>
	<div tabindex=0 @blur.capture="click_close">
		<form action="/search" method="POST">
			<div class="input-group">
				<input name="search" ref="sb" @focus="key_search" @keyup="key_search" class="form-control" v-model="search">
				<input type="submit" class="btn btn-success" value="Search">
			</div>
			<div v-if="results.length > 0" class="z-3 position-absolute bg-light">
				<ul class="list-group">
					<li class="list-group-item" v-for="r in results"><a :href="'/document/' + r.id"><strong>{{ r.title }}</strong> {{ r.subtitle }} <small>{{ r.subsubtitle }}</small></a></li>
				</ul>
			</div>
		</form>
	</div>
</template>

<script>
import { ref } from 'vue/dist/vue.esm-bundler';

export default {
	props: [
	],

	setup() {
		return {
			search: ref(""),
			searchTimer: ref(null),
			results: ref([]),
			req: ref(null),
		}
	},

	methods: {

		click_close(event) {
	    	if (!event.currentTarget.contains(event.relatedTarget)) {
				this.results = [];
			}
		},

		key_search() {
			if (this.searchTimer != null) {
				window.clearTimeout(this.searchTimer);
				this.searchTimer = null;
			}
			this.searchTimer = setTimeout(this.do_key_search, 100);
		},

		do_key_search() {
			if (this.search.length < 3) {
				this.results = [];
			} else {
				this.searchTimer = null;
				if (this.req != null) {
					this.req.abort();
					this.req = null;
				}
				this.req = $.ajax({
					url: "/api/search/title",
					method: "POST",
					data: {
						search: this.search
					}
				}).done(this.got_results);
			}
		},

		got_results(data) {
			this.results = data;
		},
		shortcut(e) {
			if (e.target.tagName == "INPUT") return;
			if (e.target.tagName == "TEXTAREA") return;
			if (e.key == "/") {
				e.preventDefault();
				$(this.$refs.sb).focus();
			}
		},
	},

	mounted() {
		$(document).on("keydown", this.shortcut);
	}
}
</script>
