<template>
  <QuickNav selected="Profile" />
  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <!-- Back -->
    <div class="text-lg text-center font-light relative px-7">
      <h1
        class="text-lg text-center px-2 py-1 absolute -left-2 -top-1"
        @click="$router.back()"
      >
        <font-awesome icon="chevron-left" class="fa-fw"></font-awesome>
      </h1>
    </div>

    <!-- 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-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-1 rounded-md ml-1"
        >
          Help
        </router-link>
      </span>
    </div>

    <div v-if="activeAccount">
      <p class="text-center mb-4">
        <b class="text-red-600">BEWARE!</b> Anyone who has this seed phrase will
        be able impersonate you and take over any digital holdings based on it.
        Reveal it when you are somewhere private, when only you can see your
        screen, and record it somewhere only you have access. A password manager
        is a good idea, and so is a piece of paper in a vault.
        <i
          >We recommend you do NOT take a screenshot or send it to any online
          service.</i
        >
      </p>

      <p v-if="numAccounts > 1">
        <b class="text-orange-600">Note:</b> You have more than one identifier
        stored in this browser. If they are all based on the same seed as the
        current identifier, this one backup is sufficient, as long as you also
        record the derivation path. However, if you have different seeds for
        other identifiers, you will have to back them up separately.
      </p>

      <div class="bg-slate-100 rounded-md overflow-hidden p-4 mb-4">
        <p v-if="showSeed" class="text-center text-slate-700 mt-2">
          {{ activeAccount.mnemonic }}
          <button
            v-show="!showCopiedSeed"
            @click="
              doCopyTwoSecRedo(
                activeAccount.mnemonic as string,
                () => (showCopiedSeed = !showCopiedSeed),
              )
            "
          >
            <font-awesome
              icon="copy"
              class="text-slate-400 fa-fw"
            ></font-awesome>
          </button>
          <span v-show="showCopiedSeed" class="text-sm text-green-500">
            Copied
          </span>
          <br />
          <br />
          Derivation Path: {{ activeAccount.derivationPath }}
          <button
            v-show="!showCopiedDeri"
            @click="
              doCopyTwoSecRedo(
                activeAccount.derivationPath as string,
                () => (showCopiedDeri = !showCopiedDeri),
              )
            "
          >
            <font-awesome
              icon="copy"
              class="text-slate-400 fa-fw"
            ></font-awesome>
          </button>
          <span v-show="showCopiedDeri" class="text-sm text-green-500"
            >Copied</span
          >
        </p>
        <button
          v-else
          class="block w-full text-center text-md uppercase bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-md"
          @click="showSeed = true"
        >
          Reveal my Seed Phrase
        </button>
      </div>
    </div>
    <div v-else>You do not have an active identity.</div>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { useClipboard } from "@vueuse/core";

import QuickNav from "../components/QuickNav.vue";
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
import { retrieveSettingsForActiveAccount } from "../db/index";
import { Account } from "../db/tables/accounts";
import * as databaseUtil from "../db/databaseUtil";
import {
  retrieveAccountCount,
  retrieveFullyDecryptedAccount,
} from "../libs/util";
import { Router } from "vue-router";
import { logger } from "../utils/logger";
@Component({ components: { QuickNav } })
export default class SeedBackupView extends Vue {
  $notify!: (notification: NotificationIface, timeout?: number) => void;
  $router!: Router;
  activeAccount: Account | null | undefined = null;
  numAccounts = 0;
  showCopiedDeri = false;
  showCopiedSeed = false;
  showSeed = false;

  // 'created' hook runs when the Vue instance is first created
  async created() {
    try {
      let activeDid = "";
      const settings = await databaseUtil.retrieveSettingsForActiveAccount();
      activeDid = settings.activeDid || "";

      if (USE_DEXIE_DB) {
        const settings = await retrieveSettingsForActiveAccount();
        activeDid = settings.activeDid || "";
      }

      this.numAccounts = await retrieveAccountCount();
      this.activeAccount = await retrieveFullyDecryptedAccount(activeDid);
    } catch (err: unknown) {
      logger.error("Got an error loading an identifier:", err);
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error Loading Profile",
          text: "Got an error loading your seed data.",
        },
        3000,
      );
    }
  }

  // call fn, copy text to the clipboard, then redo fn after 2 seconds
  doCopyTwoSecRedo(text: string, fn: () => void) {
    fn();
    useClipboard()
      .copy(text)
      .then(() => setTimeout(fn, 2000));
  }
}
</script>
