<template>
	<div class="card mb-3 shadow">
		<div class="card-header"><template v-if="user">{{user[2]}}</template><template v-else>Login</template></div>
		<div class="card-body">
			<p class="card-text row"><code class="col" v-if="banner"><pre>{{banner.join('\n')}}</pre></code><code class="col" v-if="user"><pre>{{user.join('\n')}}</pre></code></p>
		</div>
		<div class="input-group flex-nowrap" v-if="!user">
			<span class="input-group-text">🔑</span>
			<input type="password" class="form-control" placeholder="Access Code" v-model="accesscode" />
			<input type="password" class="form-control" placeholder="Verify Code" v-model="verifycode" />
			<button class="btn btn-primary" type="button" v-on:click="submit">Login<template v-if="!(accesscode || verifycode)"> (omit AV codes for SAML)</template></button>
		</div>
	</div>
</template>

<script>
	import vistax from './vistax.mjs';

	export default {
		props: {
			secret: String,
			client: Object,
			user: {
				type: Array,
				default: null
			}
		},
		emits: {
			'update:client': Object,
			'update:user': {
				type: Array,
				default: null
			}
		},
		data() {
			return {
				x_client: this.client,
				x_user: this.user,
				banner: null,
				accesscode: null,
				verifycode: null
			};
		},
		watch: {
			client(value) { this.x_client = value; },
			x_client(value) { this.$emit('update:client', value); },
			user(value) { this.x_user = value; },
			x_user(value) { this.$emit('update:user', value); }
		},
		async mounted() {
			this.x_client = await vistax.Client.fromCookie(this.secret);
			this.banner = await this.x_client.XUS_INTRO_MSG();
			if((await this.x_client.userinfo()).result) try {
				var user = await this.x_client.XUS_GET_USER_INFO();
				this.x_user = user[0] ? user : null
			} catch(ex) {
				this.x_user = null;
			}
			this.$emit('update:user', this.x_user);
			console.log('Backend secret', this.secret);
			console.log(this.banner);
		},
		methods: {
			async submit(evt) {
				var res = await ((this.accesscode && this.verifycode) ? this.x_client.authenticate(this.accesscode + ';' + this.verifycode) : this.x_client.authenticate());
				if(!!res.result[0]) {
					var user = await this.x_client.XUS_GET_USER_INFO();
					this.x_user = user[0] ? user : null
				} else this.x_user = null;
				this.$emit('update:user', this.x_user);
				console.log('Authenticate', res);
			}
		}
	};
</script>
