<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>
        [New/Edit] Identity
      </h1>
    </div>
    <form>
      <input
        type="text"
        placeholder="First Name"
        class="block w-full rounded border border-slate-400 mb-4 px-3 py-2"
        v-model="firstName"
      />
      <input
        type="text"
        placeholder="Last Name"
        class="block w-full rounded border border-slate-400 mb-4 px-3 py-2"
        v-model="lastName"
      />

      <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>
    </form>
  </section>
</template>

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

@Component({
  components: {},
})
export default class NewEditAccountView extends Vue {
  firstName =
    localStorage.getItem("firstName") === null
      ? "--"
      : localStorage.getItem("firstName");
  lastName =
    localStorage.getItem("lastName") === null
      ? "--"
      : localStorage.getItem("lastName");

  // 'created' hook runs when the Vue instance is first created
  async created() {
    await db.open();
    const settings = await db.settings.get(MASTER_SETTINGS_KEY);
    this.firstName = settings?.firstName || "";
    this.lastName = settings?.lastName || "";
  }

  onClickSaveChanges() {
    db.settings.update(MASTER_SETTINGS_KEY, {
      firstName: this.firstName,
      lastName: this.lastName,
    });
    localStorage.setItem("firstName", this.firstName as string);
    localStorage.setItem("lastName", this.lastName as string);
    this.$router.push({ name: "account" });
  }

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