<template>
  <SVGRect :rectangle="door.position" :focused="false" @click.left="on_click" />
</template>

<script lang="ts">
import { Door } from "@/lib/door";
import { AxiosError } from "axios";
import { Options, Vue } from "vue-class-component";

import SVGRect from "./SVGRect.vue";

@Options({
  components: {
    SVGRect,
  },
  props: {
    door: Door,
  },
  emits: ["doorClick", "doorSuccess", "doorFailure"],
})
export default class extends Vue {
  public door!: Door;

  public on_click() {
    this.$emit("doorClick");

    this.$advent22
      .api_get_blob(`images/${this.door.day}`)
      .then((data) => this.$emit("doorSuccess", data))
      .catch(([reason]) => {
        let msg = "Unbekannter Fehler, bitte wiederholen!";

        if (reason instanceof AxiosError) {
          if (reason.code === "ECONNABORTED") {
            // API unerreichbar
            msg = "API antwortet nicht, bitte später wiederholen!";
          } else if (reason.response !== undefined) {
            if (reason.response.status === 401) {
              // 401 UNAUTHORIZED
              msg = "Netter Versuch :)";
            } else if (reason.response.status === 422) {
              // 422 UNPROCESSABLE ENTITY
              msg = "Türchen ist kaputt, bitte Admin benachrichtigen!";
            }
          }
        }

        this.$emit("doorFailure", msg);
      });
  }
}
</script>

<style scoped>
rect {
  cursor: pointer;
}
</style>
