<template>
  <QuickNav selected="Profile"></QuickNav>
  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24">
    <!-- Heading -->
    <h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8">
      Your Identity
    </h1>

    <div class="flex justify-center py-12">
      <span />
      <span v-if="loading">
        <span class="text-xl">Creating...&nbsp;</span>
        <fa
          icon="spinner"
          class="fa-spin fa-spin-pulse"
          color="green"
          size="128"
        ></fa>
      </span>
      <span v-else>
        <span class="text-xl">Created!</span>
        <fa
          icon="burst"
          class="fa-beat px-12"
          color="green"
          style="
            --fa-animation-duration: 1s;
            --fa-animation-direction: reverse;
            --fa-animation-iteration-count: 1;
            --fa-beat-scale: 6;
          "
        ></fa>
      </span>
      <span />
    </div>
  </section>
</template>

<script lang="ts">
import "dexie-export-import";
import { Component, Vue } from "vue-facing-decorator";
import { accountsDB, db } from "@/db";
import { deriveAddress, generateSeed, newIdentifier } from "@/libs/crypto";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import QuickNav from "@/components/QuickNav";

@Component({ components: { QuickNav } })
export default class AccountViewView extends Vue {
  loading = true;

  async mounted() {
    const mnemonic = generateSeed();
    // address is 0x... ETH address, without "did:eth:"
    const [address, privateHex, publicHex, derivationPath] =
      deriveAddress(mnemonic);

    const newId = newIdentifier(address, publicHex, privateHex, derivationPath);
    const identity = JSON.stringify(newId);

    await accountsDB.open();
    await accountsDB.accounts.add({
      dateCreated: new Date().toISOString(),
      derivationPath: derivationPath,
      did: newId.did,
      identity: identity,
      mnemonic: mnemonic,
      publicKeyHex: newId.keys[0].publicKeyHex,
    });

    await db.settings.update(MASTER_SETTINGS_KEY, {
      activeDid: newId.did,
    });

    this.loading = false;
    setTimeout(() => {
      this.$router.push({ name: "account" });
    }, 1000);
  }
}
</script>
