<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">
      Seed Backup
    </h1>

    <div class="flex justify-between py-2">
      <span />
      <span>
        <router-link
          :to="{ name: 'help' }"
          class="text-xs uppercase bg-blue-500 text-white px-1.5 py-1 rounded-md ml-1"
        >
          Help
        </router-link>
      </span>
    </div>

    <div v-if="activeAccount">
      <p>
        BEWARE: Anyone who gets hold of this mnemonic seed phrase will be able
        impersonate you and take over any digital holdings based on it. So only
        reveal it when you are in a private place out of sight of other eyes,
        and only record it in something private -- don't take a screenshot or
        send it to any online service.
      </p>

      <button
        class="block w-full text-center text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md"
        @click="showSeedPhrase"
      >
        Click here when you're ready to see it.
      </button>

      <p v-if="showSeed">{{ activeAccount.mnemonic }}</p>
    </div>
    <div v-else>You do not have an active identity.</div>
    <AlertMessage
      :alertTitle="alertTitle"
      :alertMessage="alertMessage"
    ></AlertMessage>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { accountsDB, db } from "@/db";
import * as R from "ramda";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";

@Component({ components: { AlertMessage, QuickNav } })
export default class SeedBackupView extends Vue {
  activeAccount = null;
  showSeed = false;
  alertMessage = "";
  alertTitle = "";

  // 'created' hook runs when the Vue instance is first created
  async created() {
    try {
      await db.open();
      const settings = await db.settings.get(MASTER_SETTINGS_KEY);
      const activeDid = settings?.activeDid || "";

      await accountsDB.open();
      const accounts = await accountsDB.accounts.toArray();
      this.activeAccount = R.find((acc) => acc.did === activeDid, accounts);
    } catch (err) {
      console.error("Got an error loading an identity:", err);
      this.alertTitle = "Error Loading Account";
      this.alertMessage = "Got an error loading your seed data.";
    }
  }

  showSeedPhrase() {
    this.showSeed = true;
  }
}
</script>
