<template>
  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <!-- Breadcrumb -->
    <div class="mb-8">
      <!-- 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()"
        >
          <fa icon="chevron-left" class="fa-fw"></fa>
        </h1>
      </div>

      <!-- Heading -->
      <h1 id="ViewHeading" class="text-4xl text-center font-light pt-4">
        Photo
      </h1>
    </div>
    <div v-if="localImageUrl">
      Dude, you got an image! Dude, you got an image!
    </div>
    <div v-else>
      <!--
        Camera "resolution" doesn't change how it shows on screen but rather stretches the result, eg the following which just stretches it vertically:
        :resolution="{ width: 375, height: 812 }"
      -->
      <camera
        facingMode="environment"
        autoplay
        ref="camera"
        class="relative h-full"
      >
        <div class="absolute bottom-0 w-full flex justify-center pb-4">
          <!-- Button -->
          <button
            @click="storeImage"
            class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2 rounded-full"
          >
            <fa icon="camera" class="fa-fw"></fa>
          </button>
        </div>
      </camera>
    </div>
  </section>
</template>

<script lang="ts">
import axios from "axios";
import Camera from "simple-vue-camera";
import { Component, Vue } from "vue-facing-decorator";

import { DEFAULT_IMAGE_API_SERVER } from "@/constants/app";
import { getIdentity } from "@/libs/util";
import { db } from "@/db/index";
import { MASTER_SETTINGS_KEY, Settings } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto";

interface Notification {
  group: string;
  type: string;
  title: string;
  text: string;
}

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

  activeDid = "";
  localImageUrl: string | null = null;

  async mounted() {
    try {
      await db.open();
      const settings = (await db.settings.get(MASTER_SETTINGS_KEY)) as Settings;
      this.activeDid = settings?.activeDid || "";
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      console.error("Error retrieving settings from database:", err);
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error",
          text: err.message || "There was an error retrieving your settings.",
        },
        -1,
      );
    }
  }

  async storeImage(/* payload: MouseEvent */) {
    const cameraComponent = this.$refs.camera as InstanceType<typeof Camera>;
    const blob = await cameraComponent?.snapshot();
    if (!blob) {
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error",
          text: "There was an error taking the picture. Please try again.",
        },
        -1,
      );
      return;
    }

    const identifier = await getIdentity(this.activeDid);
    const token = await accessToken(identifier);
    const headers = {
      Authorization: "Bearer " + token,
    };
    const formData = new FormData();
    formData.append("image", blob, "snapshot.jpg");
    try {
      const response = await axios.post(
        DEFAULT_IMAGE_API_SERVER + "/image",
        formData,
        { headers },
      );

      console.log("Sent. Response:", response.data);
    } catch (error) {
      console.error("Error uploading the image", error);
    }
  }
}
</script>
