<script lang="ts">
  import { onMount } from "svelte";
  import { push } from "svelte-spa-router";

  // onMount( 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;
  //    });
  // });


  let qrCodeImg;
  let qrCode = "";
  let wrongCode = "";
  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;
    });
  })()

  const submitCode = async() => {
    const response = await fetch("http://transcendance:8080/api/v2/auth/2fa/check",
      {
        method : 'POST',
        headers : {
          "Content-Type": "application/json",
        },
        body : JSON.stringify({
          "twoFaCode" : qrCode,
        }),
    });
    if (response.status === 401) {
      qrCode = "";
      wrongCode = `Wrong code`;
    }
    if (response.status === 200) {
      push('/profile');
      console.log('valid Code for 2FA')
    }
  };

</script>

<!-- ask Hugo but for Reactive page might want to put main in a div or something? -->
<main>
  <h1>2FA Sign In</h1>
  <p>use google authenticator</p>
  {#await fetchQrCodeImg}
    <p>Please Wait...</p>
  {:then data}
  <!-- What the hell is data? ask Cherif -->
    <img src={qrCodeImg} alt="A QRCodeImg you must scan with google authenticator" id="qrcodeImg" />
    <form on:submit|preventDefault={submitCode}>
      <input id="code" bind:value={qrCode} type="text" placeholder="Input Code"/>
      <button type="submit">Send</button>
    </form>
    {#if wrongCode}
      <!-- shoudl i do this in the Net Ninja way? like it's "" until an error happens? -->
      <div class="error">
        {wrongCode}
      </div>
    {/if}
  {:catch}
    <p>Unable to get QrCodeImg</p>
  {/await}
</main>

<style>
  main {
    /* display: flex; */
    /* align-items: center; */
    text-align: center;
    padding-top: 40px;
    padding-bottom: 40px;
    /* max-width: 500px; */
  }

  form {
    /* max-width: 330px; */
    padding-top: 15px;

  }

  form input {
    max-width: 330px;
  }

  .error {
    font-weight: bold;
    font-size: 0.8em;
    color: red;
  }
</style>
