<template>
	<div class="castnode">
		<!--pre>CastNode {{item}} {{typeof(item)}}</pre-->
		<div v-if="editorShow">
			<input type="text" v-model="currentText" />
			<button v-on:click="saveText">Uložit</button>
			<button v-on:click="currentText = originalText;editorShow=!editorShow;">Zahodit úpravy</button>
		</div>
		<div v-else>
		<h4>{{ currentText }} </h4>
		<button v-if="editorMode" v-on:click="editorShow = !editorShow">Upravit</button>
		<button v-if="editorMode" v-on:click="deleteCast" class="delete">Smazat</button>
		</div>
	</div>
</template>

<script>
import axios from 'axios'

export default {
	name: 'CastNode',
	data: () => ({
		editorShow: false,
		currentText: "",
		originalText: "",
	}),
	props: {
		item: Object,
		editorShow: Boolean,
		editorMode: Boolean,
		create: Boolean,
		where: String,
		refnode: Object
	},
	mounted: function() {
		if (this.create){
			this.currentText = "";
			this.originalText = "";
			this.editorShow = true;
		}
		else {
			this.currentText = this.item.node.nadpis;
			this.originalText = this.item.node.nadpis;
		}

		//this.getText();
	},
	methods: {
		saveText: function() {
			console.log("Saving cast");
			console.log(this.currentText);
			if (this.create){
				console.log(this.refnode);
				console.log(this.where);
				axios.post('/api/castnode/',{
					'nadpis': this.currentText,
					'refnode': this.refnode.id,
					'where': this.where
				}).then(response => {
					this.originalText = response.data.nadpis;
					this.$root.$emit('updateData',"castNode create update");
				})
				.catch(e => {
					console.log(e);
					this.errors.push(e);
				});
			} else {
				axios.put('/api/castnode/'+this.item.node.id+'/',{
					'nadpis': this.currentText,
					'id': this.item.node.id
				}).then(response => {
					this.originalText = response.data.nadpis;
				})
				.catch(e => {
					console.log(e);
					this.errors.push(e)
				});
				
			}

			this.editorShow = false;
		},
		deleteCast: function() {
			console.log("Deleting cast");
			axios.delete('/api/castnode/'+this.item.node.id+'/'
			).then( () => {
				this.loading = false;
				this.$root.$emit('updateData',"castNode delete update");
			}).catch(e => {
				this.errors.push(e);
			});
		}
	}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.changed {
	background-color: yellow;
}
.delete {
	background-color:  #ff6666;
}
</style>
