<script>
   import ToList from "./toList.svelte";
   import Api from "../api";
   import CodeInput from "./codeInput.svelte"

   let error = "";
   let code = "";
   export let finish;
   export let id;

   export let otc = false;
   let title = otc ? "One Time Code (OTC)" : "Backup Code"
   let length = otc ? 6 : 8;

   async function sendCode() {
      let c = code.replace(/\s+/g, "");
      if (c.length < length) {
         error = `Code must be ${length} digits long!`;
      } else {
         error = "";
         let res;
         if (otc)
            res = await Api.sendOTC(id, c);
         else
            res = await Api.sendBackup(id, c);
         if (res.error)
            error = res.error;
         else
            finish(true)
      }
   }
</script>


<style>
   .actions {
      display: flex;
      align-items: center;
   }

   .btn {
      background-color: var(--primary);
      margin: 0;
      margin-left: auto;
      min-width: 80px;
   }
</style>

<h3>{title}</h3>

<CodeInput bind:value={code} label="Code" error={error} length={length} />

<div class="actions">
   <ToList {finish} />
   <button class="btn" style="margin-left: auto" on:click={sendCode}>Send</button>
</div>