<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 { Component, Vue } from "vue-facing-decorator";
import { Router } from "vue-router";

import QuickNav from "../components/QuickNav.vue";
import { NotificationIface } from "../constants/app";
import { logConsoleAndDb, retrieveSettingsForActiveAccount } from "../db/index";
import * as serverUtil from "../libs/endorserServer";
import * as libsUtil from "../libs/util";
import { errorStringForLog } from "../libs/endorserServer";

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

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

  async mounted() {
    const settings = await retrieveSettingsForActiveAccount();
    this.activeDid = settings.activeDid || "";
    this.apiServer = settings.apiServer || "";

    this.claimStr = (this.$route as Router).query["claim"];
    if (this.claimStr) {
      try {
        const veriClaim = JSON.parse(this.claimStr);
        this.claimStr = JSON.stringify(veriClaim, null, 2);
      } catch (e) {
        // ignore a parse error
      }
    } else {
      // there may be no link that uses this, meaning you'd have to enter it in a browser
      const claimJwtId = (this.$route as Router).query["claimJwtId"];
      if (claimJwtId) {
        const urlPath = libsUtil.isGlobalUri(claimJwtId)
          ? "/api/claim/byHandle/"
          : "/api/claim/";
        const url = this.apiServer + urlPath + encodeURIComponent(claimJwtId);
        const headers = await serverUtil.getHeaders(this.activeDid);

        try {
          const response = await this.axios.get(url, { headers });
          if (response.status === 200) {
            const claim = response.data?.claim;
            claim.lastClaimId = serverUtil.stripEndorserPrefix(claimJwtId);
            this.claimStr = JSON.stringify(claim, null, 2);
          } else {
            throw {
              message: "Got an error loading that claim.",
              response: {
                status: response.status,
                statusText: response.statusText,
                // url is in "fetch" response but not in AxiosResponse
              },
            };
          }
        } catch (error: unknown) {
          logConsoleAndDb(
            "Error retrieving claim: " + errorStringForLog(error),
            true,
          );
          this.$notify(
            {
              group: "alert",
              type: "danger",
              title: "Error",
              text: "Got an error retrieving claim data.",
            },
            3000,
          );
        }
      }
    }
  }

  async submitClaim() {
    const fullClaim = JSON.parse(this.claimStr);
    const result = await serverUtil.createAndSubmitClaim(
      fullClaim,
      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.",
        },
        5000,
      );
    }
  }
}
</script>
