<template>
  <QuickNav />
  <TopMessage />

  <!-- CONTENT -->
  <section id="Content" class="p-2 pb-24 max-w-3xl mx-auto">
    <!-- Breadcrumb -->
    <div>
      <!-- Back -->
      <div class="text-lg text-center font-light relative px-7">
        <h1
          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" />
        </h1>
      </div>

      <!-- Heading -->
      <h1 id="ViewHeading" class="text-4xl text-center font-light">
        Share Your Contact Info
      </h1>
    </div>

    <div class="flex justify-center mt-8">
      <button
        class="block w-fit text-center text-lg font-bold 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"
        @click="onClickShare()"
      >
        Copy to Clipboard
      </button>
    </div>
    <div class="ml-12">
      <div class="mt-8">Click to copy your info, then send it to them.</div>
      <div>
        They will paste it in the input box on the Contacts
        <font-awesome icon="users" /> screen.
      </div>
    </div>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { Router } from "vue-router";
import { useClipboard } from "@vueuse/core";
import QuickNav from "../components/QuickNav.vue";
import TopMessage from "../components/TopMessage.vue";
import { NotificationIface, APP_SERVER, USE_DEXIE_DB } from "../constants/app";
import * as databaseUtil from "../db/databaseUtil";
import { db, retrieveSettingsForActiveAccount } from "../db/index";
import { retrieveFullyDecryptedAccount } from "../libs/util";
import { generateEndorserJwtUrlForAccount } from "../libs/endorserServer";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
import { logger } from "../utils/logger";

@Component({
  components: { QuickNav, TopMessage },
})
export default class ShareMyContactInfoView extends Vue {
  $notify!: (notification: NotificationIface, timeout?: number) => void;
  $router!: Router;

  mounted() {
    logger.log("APP_SERVER in mounted:", APP_SERVER);
  }

  async onClickShare() {
    let settings = await databaseUtil.retrieveSettingsForActiveAccount();
    if (USE_DEXIE_DB) {
      settings = await retrieveSettingsForActiveAccount();
    }
    const activeDid = settings.activeDid || "";
    const givenName = settings.firstName || "";
    const isRegistered = !!settings.isRegistered;
    const profileImageUrl = settings.profileImageUrl || "";

    const account = await retrieveFullyDecryptedAccount(activeDid);

    const platformService = PlatformServiceFactory.getInstance();
    const contactQueryResult = await platformService.dbQuery(
      "SELECT COUNT(*) FROM contacts",
    );
    let numContacts =
      (databaseUtil.mapQueryResultToValues(
        contactQueryResult,
      )?.[0]?.[0] as number) || 0;
    if (USE_DEXIE_DB) {
      numContacts = await db.contacts.count();
    }

    if (account) {
      const message = await generateEndorserJwtUrlForAccount(
        account,
        isRegistered,
        givenName,
        profileImageUrl,
        true,
      );
      useClipboard()
        .copy(message)
        .then(() => {
          this.$notify(
            {
              group: "alert",
              type: "info",
              title: "Copied",
              text: "Your contact info was copied to the clipboard. Have them click on it, or paste it in the box on their 'Contacts' screen.",
            },
            5000,
          );
          if (numContacts > 0) {
            setTimeout(() => {
              this.$notify(
                {
                  group: "alert",
                  type: "success",
                  title: "Share Other Contacts",
                  text: "You may want to share some of your contacts with them. Select them below to copy and send.",
                },
                10000,
              );
            }, 3000);
          }
        });
      this.$router.push({ name: "contacts" });
    } else {
      this.$notify(
        {
          group: "alert",
          type: "error",
          title: "Error",
          text: "No account was found for the active DID.",
        },
        5000,
      );
    }
  }
}
</script>
