<template>
	<TransitionGroup>
		<div v-if="x_show" class="modal show" style="display: block;" tabindex="-1" @keydown.enter="submit" @keydown.esc="cancel">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">{{label || 'Sign'}}</h5>
						<button type="button" class="btn-close" @click="cancel"></button>
					</div>
					<div class="modal-body">
						<div class="input-group">
							<span class="input-group-text">Code</span>
							<input ref="input" type="password" class="form-control" :class="{ 'is-invalid': valid === false }" v-model="x_modelValue" @input="() => valid = null" />
							<div v-if="valid === false" class="invalid-feedback">Invalid code.</div>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-primary" :disabled="!x_modelValue" @click="submit">Submit</button>
					</div>
				</div>
			</div>
		</div>
		<div v-if="x_show" class="modal-backdrop show"></div>
	</TransitionGroup>
</template>

<style scoped>
	.v-enter-active, .v-leave-active {
		transition: opacity 0.25s ease;
	}
	.v-enter-from, .v-leave-to {
		opacity: 0;
	}
</style>

<script>
	export default {
		props: {
			client: Object,
			show: {
				type: Boolean,
				default: false
			},
			label: String,
			modelValue: null
		},
		emits: {
			'cancel': null,
			'submit': String,
			'update:show': String,
			'update:modelValue': null
		},
		data() {
			return {
				valid: null,
				x_show: this.show,
				x_modelValue: this.modelValue
			};
		},
		watch: {
			show(value) { this.x_show = value; },
			async x_show(value) {
				this.x_modelValue = '';
				this.$emit('update:show', value);
				await this.$nextTick();
				if((value) && (this.$refs.input)) this.$refs.input.focus();
			},
			modelValue(value) { this.x_modelValue = value; },
			x_modelValue(value) { this.$emit('update:modelValue', value); }
		},
		methods: {
			cancel() { this.x_show = false; },
			async submit() {
				var value = this.x_modelValue;
				if((this.client) && (value)) {
					if(this.valid = (await this.client.ORWU_VALIDSIG(' ' + value + ' ')) == '1') {
						this.x_show = false;
						this.$emit('submit', value);
					}
				}
			}
		}
	};
</script>
