<template>
	<div>
		<div v-if="editing">

			<textarea 
				ref="edval" 
				class="form-control w-100" 
				rows="5"
				type="text" 
				v-model="text"
				@keyup.esc="cancel_edit"
			></textarea>

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

		<div v-else>
			<div class="align-middle my-auto" v-html="md()"></div>
			<button @click="enable_edit" class="btn btn-secondary">
				<i class="fa fa-pencil"></i>
			</button>
		</div>

		<div ref="slotData" class="visually-hidden">
			<slot></slot>
		</div>

	</div>
</template>

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


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

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

	methods: {

		init() {
			this.load();
		},

		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;

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

		load() {
			$.ajax({
				url: this.url,
				method: "GET"
			}).done(this.loaded);
		},

		loaded(data) {
			this.text = data[0][this.field];
		},

		md() {
			var text = this.text;
			if (text == null) {
				text = "Loading...";
			}
			var txt = marked.parse(text);
			return txt;
		},
	},

	mounted() {
//		var div = document.createElement("div");
//		div.innerHTML = this.$slots.default()[0].children;
//		this.text = div.textContent;
		this.init();
	}
}
</script>
