<template>
  <QuickNav />
  <!-- CONTENT -->
  <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">
        <!-- Back -->
        <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" />
        </button>
        Raw Claim
      </h1>
    </div>

    <div class="flex">
      <textarea rows="20" class="border-2 w-full" v-model="claimStr"></textarea>
    </div>
    <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"
      @click="submitClaim()"
    >
      Sign &amp; Send
    </button>
  </section>
</template>

<script lang="ts">
import { RawAxiosRequestHeaders } from "axios";
import { IIdentifier } from "@veramo/core";
import { Component, Vue } from "vue-facing-decorator";

import GiftedDialog from "@/components/GiftedDialog.vue";
import { NotificationIface } from "@/constants/app";
import { accountsDB, db } from "@/db/index";
import { MASTER_SETTINGS_KEY, Settings } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto";
import * as serverUtil from "@/libs/endorserServer";
import QuickNav from "@/components/QuickNav.vue";
import { Account } from "@/db/tables/accounts";

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

  accountIdentityStr: string = "null";
  activeDid = "";
  apiServer = "";
  claimStr = "";

  async mounted() {
    await db.open();
    const settings = (await db.settings.get(MASTER_SETTINGS_KEY)) as Settings;
    this.activeDid = settings?.activeDid || "";
    this.apiServer = settings?.apiServer || "";

    this.claimStr = this.$route.query.claim;
    try {
      this.veriClaim = JSON.parse(this.claimStr);
      this.claimStr = JSON.stringify(this.veriClaim, null, 2);
    } catch (e) {
      // ignore a parse
    }
  }

  public async getIdentity(activeDid: string): Promise<IIdentifier> {
    await accountsDB.open();
    const account = (await accountsDB.accounts
      .where("did")
      .equals(activeDid)
      .first()) as Account;
    const identity = JSON.parse(account?.identity || "null");

    if (!identity) {
      throw new Error("Cannot submit a claim without an identifier.");
    }
    return identity;
  }

  public async getHeaders(identity: IIdentifier) {
    const headers: RawAxiosRequestHeaders = {
      "Content-Type": "application/json",
    };
    if (identity) {
      const token = await accessToken(identity);
      headers["Authorization"] = "Bearer " + token;
    }
    return headers;
  }

  // similar code is found in ProjectViewView
  async submitClaim() {
    const fullClaim = JSON.parse(this.claimStr);
    const result = await serverUtil.createAndSubmitClaim(
      fullClaim,
      await this.getIdentity(this.activeDid),
      this.apiServer,
      this.axios,
    );
    if (result.type === "success") {
      this.$notify(
        {
          group: "alert",
          type: "success",
          title: "Success",
          text: "Claim submitted.",
        },
        5000,
      );
    } else {
      console.error("Got error submitting the claim:", result);
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error",
          text: "There was a problem submitting the claim. See logs for more info.",
        },
        -1,
      );
    }
  }
}
</script>
