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

    <!-- Identity List -->

    <!-- Current Identity - Display First! -->
    <a
      href="account-view.html"
      class="block bg-slate-100 rounded-md flex items-center px-4 py-3 mb-4"
    >
      <fa icon="circle-check" class="fa-fw text-blue-600 text-xl mr-3"></fa>
      <span>
        <h2 class="text-xl font-semibold mb-0">
          {{ firstName }} {{ lastName }}
        </h2>
        <div class="text-sm text-slate-500">
          <b>ID:</b> <code>{{ activeDid }}</code>
        </div>
      </span>
    </a>

    <!-- Other Identity/ies -->
    <a
      href="account-view.html"
      class="block bg-slate-100 rounded-md flex items-center px-4 py-3 mb-4"
    >
      <fa icon="circle" class="fa-fw text-slate-400 text-xl mr-3"></fa>
      <span>
        <h2 class="text-xl font-semibold mb-0">Givenname Surname</h2>
        <div class="text-sm text-slate-500">
          <b>ID:</b> <code>did:peer:lk451kl3kl45kj41</code>
        </div>
      </span>
    </a>

    <!-- Actions -->
    <router-link
      :to="{ name: 'start' }"
      class="block text-center text-lg font-bold uppercase bg-blue-600 text-white px-2 py-3 rounded-md mb-2"
    >
      Add Another Identity&hellip;
    </router-link>
    <a
      href="start.html"
      class="block w-full text-center text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-8"
    >
      No Identity
    </a>

    <AlertMessage
      :alertTitle="alertTitle"
      :alertMessage="alertMessage"
    ></AlertMessage>
  </section>
</template>
<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { AppString } from "@/constants/app";
import { db, accountsDB } from "@/db";
import { AccountsSchema } from "@/db/tables/accounts";
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 IdentitySwitcherView extends Vue {
  Constants = AppString;
  private accounts: AccountsSchema;
  public activeDid;
  public firstName;
  public lastName;

  async created() {
    try {
      await db.open();
      const settings = await db.settings.get(MASTER_SETTINGS_KEY);
      this.activeDid = settings?.activeDid || "";
      this.apiServer = settings?.apiServer || "";
      this.apiServerInput = settings?.apiServer || "";
      this.firstName = settings?.firstName || "No";
      this.lastName = settings?.lastName || "Name";
      this.showContactGives = !!settings?.showContactGivesInline;

      const identity = await this.getIdentity(this.activeDid);

      this.publicHex = identity.keys[0].publicKeyHex;
      this.publicBase64 = Buffer.from(this.publicHex, "hex").toString("base64");
      this.derivationPath = identity.keys[0].meta.derivationPath;

      db.settings.update(MASTER_SETTINGS_KEY, {
        activeDid: identity.did,
      });
      this.checkLimits();
    } catch (err) {
      if (
        err.message ===
        "Attempted to load account records with no identity available."
      ) {
        this.limitsMessage = "No identity.";
        this.loadingLimits = false;
      } else {
        this.alertMessage =
          "Clear your cache and start over (after data backup).";
        console.error(
          "Telling user to clear cache at page create because:",
          err,
        );
        this.alertTitle = "Error Creating Account";
      }
    }
  }

  async switchAccount(accountNum: number) {
    // 0 means none
    if (accountNum === 0) {
      await db.open();
      db.settings.update(MASTER_SETTINGS_KEY, {
        activeDid: undefined,
      });
      this.activeDid = "";
      this.derivationPath = "";
      this.publicHex = "";
      this.publicBase64 = "";
    } else {
      await accountsDB.open();
      const accounts = await accountsDB.accounts.toArray();
      const account = accounts[accountNum - 1];

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

      this.activeDid = account.did;
      this.derivationPath = account.derivationPath;
      this.publicHex = account.publicKeyHex;
      this.publicBase64 = Buffer.from(this.publicHex, "hex").toString("base64");
    }
  }
}
</script>
