<script>
   import ToList from "./toList.svelte";

   export let finish;

   const states = {
      getChallenge: 0,
      requestUser: 1,
      sendChallenge: 2,
      error: 3
   }

   let state = states.getChallenge;

   let error = "";

   const onError = err => {
      state = states.error;
      error = err.message;
   };

   let challenge;

   async function requestUser() {
      state = states.requestUser;
      let res = await window.navigator.credentials.get({
         publicKey: challenge
      })
      state = states.sendChallenge();
      let r = res.response;
      let data = encode({
         authenticatorData: r.authenticatorData,
         clientDataJSON: r.clientDataJSON,
         signature: r.signature,
         userHandle: r.userHandle
      });
      let {
         success
      } = fetch("https://localhost:8444/auth", {
         body: data,
         method: "POST"
      }).then(res => res.json())
      if (success) {
         finish(true);
      }
   }

   async function getChallenge() {
      state = states.getChallenge;
      challenge = await fetch("https://localhost:8444/auth")
         .then(res => res.arrayBuffer())
         .then(data => decode(MessagePack.Buffer.from(data)));

      requestUser().catch(onError);
   }
   getChallenge().catch(onError)
</script>


<style>
   :root {
      --error: red;
   }

   .error {
      color: var(--error);
   }
</style>

<h3>U2F Security Key</h3>
<h4>This Method is currently not supported. Please choose another one!</h4>
<ToList {finish} />