<template>
  <section id="Content" class="p-6 pb-24">
    <!-- 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" class="fa-fw"></fa>
        </button>
        Edit Identity
      </h1>
    </div>

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

    <div class="mt-8">
      <button
        type="button"
        class="block w-full text-center text-lg font-bold uppercase bg-blue-600 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-slate-500 text-white px-1.5 py-2 rounded-md"
        @click="onClickCancel()"
      >
        Cancel
      </button>
    </div>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { db } from "@/db/index";
import { MASTER_SETTINGS_KEY, Settings } from "@/db/tables/settings";

@Component({
  components: {},
})
export default class NewEditAccountView extends Vue {
  givenName = "";

  // 'created' hook runs when the Vue instance is first created
  async created() {
    await db.open();
    const settings = (await db.settings.get(MASTER_SETTINGS_KEY)) as Settings;
    this.givenName =
      (settings?.firstName || "") +
      (settings?.lastName ? ` ${settings.lastName}` : ""); // deprecated, pre v 0.1.3
  }

  onClickSaveChanges() {
    db.settings.update(MASTER_SETTINGS_KEY, {
      firstName: this.givenName,
      lastName: "", // deprecated, pre v 0.1.3
    });
    localStorage.setItem("firstName", this.givenName as string);
    localStorage.setItem("lastName", ""); // deprecated, pre v 0.1.3
    this.$router.back();
  }

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