<script>
import {fetchGet, fetchPost} from "@/utilities/fetch.js";
import QRCode from "qrcode";

export default {
	name: "totp",
	async setup(){
		let l = ""
		await fetchGet("/api/Welcome_GetTotpLink", {}, (res => {
			if (res.status) l = res.data;
		}));
		return {l}
	},
	mounted() {
		if (this.l) {
			QRCode.toCanvas(document.getElementById('qrcode'), this.l, function (error) {})
		}
	},
	data(){
		return {
			totp: "",
			totpInvalidMessage: "",
			verified: false
		}
	},
	methods: {
		validateTotp(){
			
		}	
	},
	watch: {
		totp(newVal){
			const input = document.querySelector("#totp");
			input.classList.remove("is-invalid", "is-valid")
			if (newVal.length === 6){
				console.log(newVal)
				if (/[0-9]{6}/.test(newVal)){
					fetchPost("/api/Welcome_VerifyTotpLink", {
						totp: newVal
					}, (res) => {
						if (res.status){
							this.verified = true;
							input.classList.add("is-valid");
							this.$emit("verified")
						}else{
							input.classList.add("is-invalid")
							this.totpInvalidMessage = "TOTP does not match."
						}
					})
				}else{
					input.classList.add("is-invalid");
					this.totpInvalidMessage = "TOTP can only contain numbers"
				}
			}
		}
	}
}
</script>

<template>
	<div class="mb-3">
		<p class="mb-2"><small class="text-muted">1. Please scan the following QR Code to generate TOTP</small></p>
		<canvas id="qrcode" class="rounded-3 mb-2"></canvas>
		<div class="p-3 bg-body-secondary rounded-3 border mb-3">
			<p class="text-muted mb-0"><small>Or you can click the link below:</small>
			</p><a :href="this.l"><code style="line-break: anywhere">{{this.l}}</code></a>
		</div>
		<label for="totp" class="mb-2"><small class="text-muted">2. Enter the TOTP generated by your authenticator to verify</small></label>
		<div class="form-group">
			<input class="form-control text-center totp"
			       id="totp" maxlength="6" type="text" inputmode="numeric" autocomplete="one-time-code"
			       v-model="this.totp"
			       :disabled="this.verified"
			>
			<div class="invalid-feedback">
				{{this.totpInvalidMessage}}
			</div>
			<div class="valid-feedback">
				TOTP verified!
			</div>
		</div>
	</div>
</template>

<style scoped>
	
</style>