<template>
	<ViewDocEdit v-if="(can_edit) && (is_editing)" :client="client" :dfn="dfn" :ien="ien" @update="x => $emit('update', x)" @accept="doc_accept" />
	<div v-else class="card mb-3 shadow">
		<div class="card-header d-flex justify-content-between align-items-center">
			<span>{{localtitle || 'Document'}}</span>
			<span>
				<a v-if="can_delete" class="widget" @click="() => $emit('delete', ien)">🗑</a>
				<a v-if="can_edit" class="widget" @click="() => is_editing = true">✏</a>
				<a v-if="can_sign" class="widget" @click="() => $emit('sign', ien)">🔏</a>
				<a class="widget" @click="() => $emit('cancel')">❌</a>
			</span>
		</div>
		<div class="card-body">{{text}}</div>
	</div>
</template>

<style scoped>
	a.widget {
		cursor: default;
		text-decoration: none;
	}
	div.card-body {
		tab-size: 8;
	}
</style>

<script>
	import ViewDocEdit from './ViewDocEdit.vue';

	export default {
		components: {
			ViewDocEdit
		},
		props: {
			client: Object,
			dfn: String,
			ien: String,
		},
		emits: {
			'cancel': null,
			'sign': null,
			'update': Object,
			'delete': String
		},
		data() {
			return {
				text: null,
				can_sign: null,
				can_edit: null,
				can_delete: null
			};
		},
		computed: {
			is_editing: {
				get() { return this.$route.query.hasOwnProperty('edit'); },
				set(value) {
					var query = { ...this.$route.query };
					if(value) query.edit = '';
					else delete query.edit;
					this.$router.replace({ query });
				}
			},
			localtitle() {
				var doc = this.text;
				if(doc) {
					var brk = doc.indexOf('\r\n');
					if(brk >= 0) {
						doc = doc.substring(0, brk);
						brk = doc.indexOf(': ');
						if(brk >= 0) return doc.substring(brk + 2).replace(/^\s+|\s+$/g, '');
						else return doc.replace(/^\s+|\s+$/g, '');
					}
				}
			}
		},
		methods: {
			async doc_accept() {
				this.text = await this.client.TIU_GET_RECORD_TEXT(this.ien);
				this.is_editing = false;
			}
		},
		created() {
			this.$watch(
				() => (this.client, this.ien, {}),
				async function() {
					this.text = this.can_edit = this.can_delete = null;
					if((this.client) && (this.ien)) {
						this.text = await this.client.TIU_GET_RECORD_TEXT(this.ien);
						this.can_sign = (await this.client.TIU_AUTHORIZATION(this.ien, 'SIGNATURE') == '1') || (await this.client.TIU_AUTHORIZATION(this.ien, 'COSIGNATURE') == '1');
						this.can_edit = await this.client.TIU_AUTHORIZATION(this.ien, 'EDIT RECORD') == '1';
						this.can_delete = await this.client.TIU_AUTHORIZATION(this.ien, 'DELETE RECORD') == '1';
					}
				},
				{ immediate: true }
			);
		}
	};
</script>
