<template>
  <section>
    <div class="content">
      <p class="title is-5">Steuerung</p>
      <ul>
        <li>Linksklick: Türchen auswählen</li>
        <li>Tastatur [0]-[9], [Rücktaste]: Tag eingeben</li>
        <li>Tastatur [Enter]: Tag speichern</li>
        <li>Tastatur [Esc]: Eingabe Abbrechen</li>
        <li>Tastatur [Entf]: Tag entfernen</li>
      </ul>
    </div>
    <figure class="image">
      <img src="@/assets/adventskalender.jpg" />
      <ThouCanvas>
        <template v-for="(door, index) in doors" :key="`door-${index}`">
          <SVGRectText
            v-if="door.day >= 0"
            :text="String(door.day)"
            :rectangle="door.position"
          />
          <SVGRect
            :rectangle="door.position"
            :focused="index === focused"
            @click.left="click_door(index)"
          />
        </template>
      </ThouCanvas>
    </figure>
  </section>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { Door } from "./calendar";

import ThouCanvas from "../rects/ThouCanvas.vue";
import SVGRect from "../rects/SVGRect.vue";
import SVGRectText from "../rects/SVGRectText.vue";

@Options({
  components: {
    ThouCanvas,
    SVGRect,
    SVGRectText,
  },
  props: {
    doors: Array,
  },
  emits: ["update:doors"],
})
export default class extends Vue {
  private doors!: Door[];
  private focused = -1;

  private click_door(index: number) {
    if (this.focused >= 0) {
      return;
    }

    this.focused = index;

    const listener = (() => {
      let old_day = this.doors[index].day;
      let num_input = "";

      return (event: KeyboardEvent) => {
        if (event.key >= "0" && event.key <= "9") {
          // number input

          num_input += event.key;
          this.doors[this.focused].day = Number(num_input);
        } else if (event.key === "Backspace") {
          // remove char

          num_input = num_input.slice(0, -1);
          this.doors[this.focused].day = Number(num_input);
        } else if (event.key === "Enter") {
          // accept

          this.focused = -1;
          window.removeEventListener("keydown", listener);
        } else if (event.key === "Escape") {
          // abort

          this.doors[this.focused].day = old_day;
          this.focused = -1;
          window.removeEventListener("keydown", listener);
        } else if (event.key === "Delete") {
          // delete

          this.doors[this.focused].day = -1;
          this.focused = -1;
          window.removeEventListener("keydown", listener);
        }
      };
    })();

    window.addEventListener("keydown", listener);
  }

  public beforeUnmount() {
    this.$emit("update:doors", this.doors);
  }
}
</script>

<style lang="scss" scoped>
section > figure {
  user-select: none;

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