<script lang="ts">

  import { onMount } from 'svelte';
  import { loginStatus } from '../stores/loginStatusStore';

  // Cherif's code

  let qrCodeImg;
	let qrCode = "";
	let wrongCode = "";
	let maxTry = 3;
	// const fetchQrCodeImg = (async() => {
	// 	await fetch("http://transcendance:8080/api/v2/auth/2fa/generate",
	// 	{
	// 		method: 'POST',
	// 	})
	// 	.then(response => {return response.blob()})
	// 	.then(blob => {
	// 		const url = URL.createObjectURL(blob);
	// 		qrCodeImg = url;
	// 	});
	// })()

  // $: submit = async() => {
	// 	const response = await fetch("http://transcendance:8080/api/v2/auth/2fa/turn-on",
	// 	{
	// 		method : 'POST',
	// 		headers : {
	// 			"Content-Type": "application/json",
	// 		},
	// 		body : JSON.stringify({
	// 			"twoFaCode" : qrCode,
	// 		}),
	// 	});
	// 	if (response.status === 401)
	// 	{
	// 		qrCode = "";
	// 		wrongCode = `Wrong code, please try again. You have ${maxTry} before end session`;
	// 		maxTry--;
	// 	}
	// 	if (maxTry === 0)
	// 	{
	// 		await fetch("http://transcendance:8080/auth/logout",
	// 		{
	// 			method : 'POST',
	// 		})
	// 		.then(response => response.json())
	// 		.then(push("/login"));
	// 	}
	// 	if (response.status === 200)
	// 	{
	// 		push("/");
	// 	}
	// }



  // My code



  let auth;
  // we're expecting secret and otpauth

  onMount( async() => {
    // auth = await fetch('http://transcendance:8080/api/v2/auth/2fa/generate', {
    //     method: 'POST'
    //   })
		//   .then((resp) => resp.json());
    // console.log(auth.secret);

    await fetch("http://transcendance:8080/api/v2/auth/2fa/generate", {
        method: 'POST',
      })
      .then(response => {return response.blob()})
      .then(blob => {
        const url = URL.createObjectURL(blob);
        qrCodeImg = url;
		});

  });

  // testing loginStatus Custom Store

  const toggleTFA = () => {
    loginStatus.toggleTFA();
    console.log($loginStatus.tfa);
  }


  // testing

  let auth2
  const TFA = async() => {
    // ok no idea what goes in here...
    auth2 = await fetch('http://transcendance:8080/api/v2/auth/2fa/generate', {
        method: 'POST'
      })
		  // .then((resp) => resp.json());

    // console.log(auth2.secret);
    console.log(auth2);
  };

  // if ($loginStatus.tfa && $loginStatus.fortyTwo)

</script>

<h1>2FA Test</h1>

<div>
  <button on:click={TFA}>TFA</button>
</div>

<div>
  {#if auth2}
    <p>{auth2.json()}</p>
  {/if}
</div>

<img src={qrCodeImg} alt="A QRCodeImg you must scan with google authenticator" id="qrcodeImg" />


<!-- <p>FortyTwo: {$loginStatus.fortyTwo}</p>
<p>TFA: {$loginStatus.tfa}</p>
<p>isLogged: {loginStatus.isLogged}</p>

<div>
  <button on:click={toggleTFA}>toggleTFA</button>
</div> -->




<style>

</style>