<script>
   import Api, {
      TFATypes
   } from "./api";
   import Icon from "./icons/Icon.svelte";

   import OTCTwoFactor from "./twofactors/otc.svelte";
   import PushTwoFactor from "./twofactors/push.svelte";
   import U2FTwoFactor from "./twofactors/u2f.svelte";

   const states = {
      list: 1,
      twofactor: 2
   }

   function getIcon(tf) {
      switch (tf.type) {
         case TFATypes.OTC:
            return "Authenticator"
         case TFATypes.BACKUP_CODE:
            return "BackupCode"
         case TFATypes.U2F:
            return "SecurityKey"
         case TFATypes.APP_ALLOW:
            return "AppPush"
      }
   }

   let twofactors = Api.twofactor.map(tf => {
      return {
         ...tf,
         icon: getIcon(tf)
      }
   });

   let state = states.list;

   let twofactor = undefined;
   twofactor = twofactors[0];
   $: console.log(twofactor)

   function onFinish(res) {
      if (res)
         finish()
      else
         twofactor = undefined;
   }

   export let finish;
</script>

<style>
   ul {
      list-style: none;
      padding-inline-start: 0;
      margin-bottom: 0;
   }

   li {
      border-top: 1px grey solid;
      padding: 1em;
      cursor: pointer;
   }

   li:first-child {
      border-top: none !important;
   }

   .icon {
      float: left;
      height: 24px;
      width: 24px;
   }

   .name {
      margin-left: 48px;
      line-height: 24px;
      font-size: 20px;
   }
</style>

<div>
   {#if !twofactor} 
   <h3>Select your Authentication method:</h3>
   <ul>
      {#each twofactors as tf}
      <li on:click={()=>twofactor = tf}>
         <div class="icon">
            <Icon icon_name={tf.icon}/>
         </div>

         <div class="name">
            {tf.name}
         </div>
      </li>
      {/each}
   </ul>
   {:else}
      {#if twofactor.type === TFATypes.OTC}
         <OTCTwoFactor id={twofactor.id} finish={onFinish}  otc={true}/>
      {:else if twofactor.type === TFATypes.BACKUP_CODE}
         <OTCTwoFactor id={twofactor.id}  finish={onFinish} otc={false}/>
      {:else if twofactor.type === TFATypes.U2F}
         <U2FTwoFactor id={twofactor.id} finish={onFinish}/>
      {:else if twofactor.type === TFATypes.APP_ALLOW}
         <PushTwoFactor id={twofactor.id}  finish={onFinish}/>
      {:else}
         <div>Invalid TwoFactor Method!</div>
      {/if}
   {/if}

</div>