<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
          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>
        </button>
        Edit Identity
      </h1>
    </div>

    <input
      v-model="givenName"
      type="text"
      placeholder="Name"
      class="block w-full rounded border border-slate-400 mb-4 px-3 py-2"
    />

    <div class="mt-8">
      <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
        <button
          type="button"
          class="block w-full text-center text-lg font-bold 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-2 py-3 rounded-md mb-2"
          @click="onClickSaveChanges()"
        >
          Save Changes
        </button>
        <!-- SHOW ME instead while processing saving changes -->
        <button
          type="button"
          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-2 py-3 rounded-md mb-2"
          @click="onClickCancel()"
        >
          Cancel
        </button>
      </div>
    </div>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { Router } from "vue-router";

import { USE_DEXIE_DB } from "@/constants/app";
import { db, retrieveSettingsForActiveAccount } from "../db/index";
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
import * as databaseUtil from "../db/databaseUtil";

@Component({
  components: {},
})
export default class NewEditAccountView extends Vue {
  $router!: Router;

  givenName = "";

  // 'created' hook runs when the Vue instance is first created
  async created() {
    let settings = await databaseUtil.retrieveSettingsForActiveAccount();
    if (USE_DEXIE_DB) {
      settings = await retrieveSettingsForActiveAccount();
    }
    this.givenName =
      (settings.firstName || "") +
      (settings.lastName ? ` ${settings.lastName}` : ""); // deprecated, pre v 0.1.3
  }

  async onClickSaveChanges() {
    await databaseUtil.updateDefaultSettings({
      firstName: this.givenName,
      lastName: "", // deprecated, pre v 0.1.3
    });
    if (USE_DEXIE_DB) {
      await db.settings.update(MASTER_SETTINGS_KEY, {
        firstName: this.givenName,
        lastName: "", // deprecated, pre v 0.1.3
      });
    }
    this.$router.back();
  }

  onClickCancel() {
    this.$router.back();
  }
}
</script>
