<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="{ width: 375, height: 812 }"
        facingMode="user"
        autoplay
        ref="camera"
      >
        <button @click="storeImage">I'm on top of the video</button>
      </camera>
    </div>
  </section>
</template>

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

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;

  localImageUrl: string | null = null;

  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;
    }

    //this.localImageUrl = URL.createObjectURL(blob);

    console.log("Got an image:", blob?.size);

    const formData = new FormData();
    formData.append("image", blob, "snapshot.jpg");
    try {
      const response = await axios.post(
        "http://localhost:3000/image",
        formData,
      );

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