<template>
  <svg
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 1000 1000"
    preserveAspectRatio="none"
    @contextmenu.prevent
    @mousedown="transform_mouse_event"
    @mousemove="transform_mouse_event"
    @mouseup="transform_mouse_event"
    @click="transform_mouse_event"
    @dblclick="transform_mouse_event"
  >
    <slot name="default" />
  </svg>
</template>

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

function get_event_thous(event: MouseEvent): Vector2D {
  if (event.currentTarget === null) {
    return new Vector2D();
  }

  const target = event.currentTarget as Element;

  return new Vector2D(
    Math.round((event.offsetX / target.clientWidth) * 1000),
    Math.round((event.offsetY / target.clientHeight) * 1000)
  );
}

function mouse_event_validator(event: object, point: object): boolean {
  if (!(event instanceof MouseEvent)) {
    console.warn(event, "is not a MouseEvent!");
    return false;
  }

  if (!(point instanceof Vector2D)) {
    console.warn(point, "is not a Vector2D!");
    return false;
  }

  return true;
}

@Options({
  emits: {
    mousedown: mouse_event_validator,
    mouseup: mouse_event_validator,
    mousemove: mouse_event_validator,
    click: mouse_event_validator,
    dblclick: mouse_event_validator,
  },
})
export default class ThouCanvas extends Vue {
  private transform_mouse_event(event: MouseEvent) {
    const point = get_event_thous(event);
    this.$emit(event.type, event, point);
  }
}
</script>

<style scoped>
svg {
  height: 100%;
  width: 100%;
}
</style>