<template>
  <QuickNav selected="Profile"></QuickNav>
  <section>
    <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;

  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 || "";
      this.lastName = settings?.lastName || "";
      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>
