<template>
	<div class="ulohavzoraknode">
		<!--pre>UlohaVzorakNode {{item}} {{typeof(item)}}</pre-->
		<h5>Řešení {{item.node.uloha.cislo_zadani.poradi}}.{{ item.node.uloha.kod }}: {{ item.node.uloha.nazev }}</h5>
		<button v-if="editorMode" v-on:click="showSelect=!showSelect" class="upravit">Upravit</button>
		<div v-if="showSelect">
			<form class="searchForm" v-on:submit.prevent="submitSearch">
				<input type="text" v-model="searchQuery" placeholder="Napište název" @keyup="submitSearch">
			</form>
			<div class="searchResult" v-show="isResult">
				<ul>
					<li v-for="res in searchResults" :key="res.id" v-on:click="setSelected(res)">{{res.nazev}}</li>
				</ul>
			</div>
		</div>
	</div>
</template>

<script>
import axios from 'axios'

export default {
	name: 'UlohaVzorakNode',
	data: () => {
		return {
			isResult: false,
			searchQuery: '',
			searchResults: [],
			showSelect: false,
			selected: null,
			selected_id: null
		}
	},
	props: {
		item: Object,
		create: Boolean,
		showSelect: Boolean,
	},
	mounted: function(){
		if (this.item.node.uloha === null){
			console.log("Uloha je null!");
			console.log(this.item);
		}
		if (this.create){
			this.showSelect = true;
			console.log('Creating');
		}
	},
	methods: {
		submitSearch: function(){
			if (this.searchQuery.length < 3) { return;}
			var reqURL = "/api/ulohavzoraknode/?nazev="+this.searchQuery;
			axios.get(reqURL).then( (response) => {
				this.searchResults = response.data.results;
				this.isResult = true;
				console.log("Got:");
				console.log(this.searchResults);
			}).catch( (err) => { /* fail response msg */
				console.log(err);
			});
		},
		setSelected: function(res){
			this.searchQuery = res.nazev
			this.selected_id = res.id
		}
	}
}
</script>

<style scoped>
.upravit {
	margin-top:-40px;
}
</style>