<template>
  <div class="panel-block is-flex-direction-column">
    <div class="content" style="width: 100%">
      <h3>Steuerung</h3>
      <ul>
        <li>Linksklick + Ziehen: Neues Türchen erstellen</li>
        <li>Rechtsklick + Ziehen: Türchen verschieben</li>
        <li>Doppel- oder Mittelklick: Türchen löschen</li>
      </ul>
    </div>
    <figure class="image is-unselectable">
      <img :src="$advent22.api_url('general/background')" />
      <RectangleCanvas
        :rectangles="rectangles"
        @draw="on_draw"
        @drag="on_drag"
        @remove="on_remove"
      />
    </figure>
  </div>
</template>

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

import RectangleCanvas from "./RectangleCanvas.vue";

@Options({
  components: {
    RectangleCanvas,
  },
  props: {
    doors: Array,
  },
  emits: ["update:doors"],
})
export default class extends Vue {
  private doors!: Door[];

  public get rectangles() {
    return this.doors.map((door) => door.position);
  }

  public on_draw(position: Rectangle) {
    this.doors.push(new Door(position));
  }

  public find_door_index(position: Rectangle): number {
    return this.doors.findIndex((door) => door.position.equals(position));
  }

  public on_drag(old_pos: Rectangle, new_pos: Rectangle) {
    const idx = this.find_door_index(old_pos);

    if (idx === -1) {
      return;
    }

    this.doors[idx].position = new_pos;
  }

  public on_remove(position: Rectangle) {
    const idx = this.find_door_index(position);

    if (idx === -1) {
      return;
    }

    this.doors.splice(idx, 1);
  }

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