<template>
	<div>
		<div v-if="editing" class="input-group">

			<input 
				ref="edval" 
				class="form-control" 
				type="text" 
				v-model="text"
				@keyup.enter="submit_edit"
				@keyup.esc="cancel_edit"
			>

			<button @click="cancel_edit" class="btn btn-danger px-1 py-0">
				<i class="fa fa-close"></i>
			</button>
			<button @click="submit_edit" class="btn btn-success px-1 py-0">
				<i class="fa fa-check"></i>
			</button>
		</div>

		<div v-else class="d-flex justify-content-between align-middle">
			<span class="align-middle my-auto">{{ text }}</span>
			<button @click="enable_edit" class="btn btn-secondary px-1 py-0">
				<i class="fa fa-pencil"></i>
			</button>
		</div>

	</div>
</template>

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


export default {
	props: [
		"value",
		"url",
		"field",
	],

	setup() {
		return {
			editing: ref(false),
			text: ref(""),
			saved: ref(""),
		}
	},

	methods: {

		enable_edit() {
			this.editing = true;
			this.saved = this.text;
			var that = this;
			setTimeout(function() { $(that.$refs.edval).focus() }, 100);
		},

		cancel_edit() {
			this.text = this.saved;
			this.editing = false;
		},

		submit_edit() {

			var data = {};
			data[this.field] = this.text;

			console.log(data);

			$.ajax({
				url: this.url,
				method: "POST",
				data: data
			});
			this.editing = false;
		},
	},

	mounted() {
		this.text = this.value;
	}
}
</script>
