<template>
  <QuickNav />
  <TopMessage />

  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <!-- 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"></font-awesome>
      </h1>
    </div>

    <!-- Heading -->
    <h1 id="ViewHeading" class="text-4xl text-center font-light px-4 mb-4">
      Beginning of BVC Saturday Meeting
    </h1>

    <div>
      <h2 class="text-2xl m-2">You're Here</h2>
      <div class="m-2 flex">
        <input v-model="attended" type="checkbox" class="h-6 w-6" />
        <span class="pb-2 pl-2 pr-2">Attended</span>
      </div>
      <div class="m-2 flex">
        <input v-model="gaveTime" type="checkbox" class="h-6 w-6" />
        <span class="pb-2 pl-2 pr-2">Spent Time</span>
        <span v-if="gaveTime">
          <input
            v-model="hoursStr"
            type="text"
            placeholder="How much time"
            size="1"
            class="border border-slate-400 h-6 px-2"
          />
          hour(s)
        </span>
        <!-- This is to match input height to avoid shifting when hiding & showing. -->
        <span v-else class="h-6" />
      </div>
    </div>

    <div
      v-if="attended || (gaveTime && hoursStr && hoursStr != '0')"
      class="flex justify-center mt-4"
    >
      <button
        class="block text-center text-md 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 w-56"
        @click="record()"
      >
        Sign & Send
      </button>
    </div>
    <div v-else class="flex justify-center mt-4">
      <button
        class="block text-center text-md font-bold bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-2 py-3 rounded-md w-56"
      >
        Select Your Actions
      </button>
    </div>
  </section>
</template>

<script lang="ts">
import axios from "axios";
import { DateTime } from "luxon";
import { Router } from "vue-router";
import { Component, Vue } from "vue-facing-decorator";

import QuickNav from "../components/QuickNav.vue";
import TopMessage from "../components/TopMessage.vue";
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
import * as databaseUtil from "../db/databaseUtil";
import { retrieveSettingsForActiveAccount } from "../db/index";
import {
  BVC_MEETUPS_PROJECT_CLAIM_ID,
  bvcMeetingJoinClaim,
  createAndSubmitClaim,
  createAndSubmitGive,
} from "../libs/endorserServer";
import * as libsUtil from "../libs/util";
import { logger } from "../utils/logger";
@Component({
  components: {
    QuickNav,
    TopMessage,
  },
})
export default class QuickActionBvcBeginView extends Vue {
  $notify!: (notification: NotificationIface, timeout?: number) => void;
  $router!: Router;
  attended = true;
  gaveTime = true;
  hoursStr = "1";
  todayOrPreviousStartDate = "";

  async mounted() {
    // use the time zone for Bountiful
    let currentOrPreviousSat = DateTime.now().setZone("America/Denver");
    if (currentOrPreviousSat.weekday < 6) {
      // it's not Saturday or Sunday,
      // so move back one week before setting to the Saturday
      currentOrPreviousSat = currentOrPreviousSat.minus({ week: 1 });
    }
    const eventStartDateObj = currentOrPreviousSat
      .set({ weekday: 6 })
      .set({ hour: 9 })
      .startOf("hour");

    // Hack, but full ISO pushes the length to 340 which crashes verifyJWT!
    this.todayOrPreviousStartDate =
      eventStartDateObj.toISO({
        suppressMilliseconds: true,
      }) || "";
  }

  async record() {
    let settings = await databaseUtil.retrieveSettingsForActiveAccount();
    if (USE_DEXIE_DB) {
      settings = await retrieveSettingsForActiveAccount();
    }
    const activeDid = settings.activeDid || "";
    const apiServer = settings.apiServer || "";

    try {
      const hoursNum = libsUtil.numberOrZero(this.hoursStr);

      this.$notify({ group: "alert", type: "toast", title: "Sent..." }, 1000);

      // first send the claim for time given
      let timeSuccess = false;
      if (this.gaveTime && hoursNum > 0) {
        const timeResult = await createAndSubmitGive(
          axios,
          apiServer,
          activeDid,
          activeDid,
          undefined,
          undefined,
          hoursNum,
          "HUR",
          BVC_MEETUPS_PROJECT_CLAIM_ID,
        );
        if (timeResult.type === "success") {
          timeSuccess = true;
        } else {
          logger.error("Error sending time:", timeResult);
          this.$notify(
            {
              group: "alert",
              type: "danger",
              title: "Error",
              text:
                timeResult?.error?.userMessage ||
                "There was an error sending the time.",
            },
            5000,
          );
        }
      }

      // now send the claim for attendance
      let attendedSuccess = false;
      if (this.attended) {
        const attendResult = await createAndSubmitClaim(
          bvcMeetingJoinClaim(activeDid, this.todayOrPreviousStartDate),
          activeDid,
          apiServer,
          axios,
        );
        if (attendResult.type === "success") {
          attendedSuccess = true;
        } else {
          logger.error("Error sending attendance:", attendResult);
          this.$notify(
            {
              group: "alert",
              type: "danger",
              title: "Error",
              text:
                attendResult?.error?.userMessage ||
                "There was an error sending the attendance.",
            },
            5000,
          );
        }
      }

      if (timeSuccess || attendedSuccess) {
        const actions =
          timeSuccess && attendedSuccess
            ? "Your attendance and time have been recorded."
            : timeSuccess
              ? "Your time has been recorded."
              : "Your attendance has been recorded.";
        this.$notify(
          {
            group: "alert",
            type: "success",
            title: "Success",
            text: actions,
          },
          3000,
        );
        this.$router.push({ path: "/quick-action-bvc" });
      }

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      logger.error("Error sending claims.", error);
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error",
          text: error.userMessage || "There was an error sending the claims.",
        },
        5000,
      );
    }
  }
}
</script>
