<template>
  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <!-- Breadcrumb -->
    <div id="ViewBreadcrumb" class="mb-8">
      <h1 class="text-lg text-center font-light relative px-7">
        <!-- Cancel -->
        <button
          @click="$router.go(-1)"
          class="text-lg text-center px-2 py-1 absolute -left-2 -top-1"
        >
          <fa icon="chevron-left"></fa>
        </button>
        Import Existing Identity
      </h1>
    </div>
    <!-- Import Account Form -->
    <p class="text-center text-xl mb-4 font-light">
      Enter your seed phrase below to import your identity on this device.
    </p>
    <!-- id used by puppeteer test script -->
    <input
      id="seed-input"
      type="text"
      placeholder="Seed Phrase"
      class="block w-full rounded border border-slate-400 mb-4 px-3 py-2"
      v-model="mnemonic"
    />
    {{ mnemonic }}
    <h3
      class="text-sm uppercase font-semibold mb-3"
      @click="showAdvanced = !showAdvanced"
    >
      Advanced
    </h3>
    <div v-if="showAdvanced">
      Enter a custom derivation path
      <input
        type="text"
        class="block w-full rounded border border-slate-400 mb-4 px-3 py-2"
        v-model="derivationPath"
      />
      For previous uPort or Endorser users,
      <a @click="derivationPath = UPORT_DERIVATION_PATH" class="text-blue-500">
        click here to use that value.
      </a>
    </div>
    <div class="mt-8">
      <button
        @click="from_mnemonic()"
        class="block w-full text-center text-lg font-bold uppercase bg-blue-600 text-white px-2 py-3 rounded-md mb-2"
      >
        Import
      </button>
      <button
        @click="onCancelClick()"
        type="button"
        class="block w-full text-center text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md"
      >
        Cancel
      </button>
    </div>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import {
  DEFAULT_ROOT_DERIVATION_PATH,
  deriveAddress,
  newIdentifier,
} from "../libs/crypto";
import { accountsDB, db } from "@/db/index";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";

@Component({
  components: {},
})
export default class ImportAccountView extends Vue {
  UPORT_DERIVATION_PATH = "m/7696500'/0'/0'/0'"; // for legacy imports, likely never used

  mnemonic = "";
  address = "";
  privateHex = "";
  publicHex = "";
  derivationPath = DEFAULT_ROOT_DERIVATION_PATH;
  showAdvanced = false;

  public onCancelClick() {
    this.$router.back();
  }

  public async from_mnemonic() {
    const mne: string = this.mnemonic.trim().toLowerCase();
    if (this.mnemonic.trim().length > 0) {
      [this.address, this.privateHex, this.publicHex] = deriveAddress(
        mne,
        this.derivationPath,
      );

      const newId = newIdentifier(
        this.address,
        this.publicHex,
        this.privateHex,
        this.derivationPath,
      );

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

        // record that as the active DID
        await db.open();
        db.settings.update(MASTER_SETTINGS_KEY, {
          activeDid: newId.did,
        });
        this.$router.push({ name: "account" });
      } catch (err) {
        console.error("Error saving mnemonic & updating settings:", err);
      }
    }
  }
}
</script>
