<template>
  <svg
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    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 setup lang="ts">
import { Vector2D } from "@/lib/rects/vector2d";

function get_event_thous(event: MouseEvent): Vector2D {
  if (!(event.currentTarget instanceof SVGSVGElement)) {
    return new Vector2D();
  }

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

type TCEventType = "mousedown" | "mousemove" | "mouseup" | "click" | "dblclick";

const is_tceventtype = (t: unknown): t is TCEventType =>
  t === "mousedown" || t === "mousemove" || t === "mouseup" || t === "click" || t === "dblclick";

const emit = defineEmits<{
  (event: TCEventType, e: MouseEvent, point: Vector2D): void;
}>();

function transform_mouse_event(event: MouseEvent): void {
  if (!is_tceventtype(event.type)) return;

  emit(event.type, event, get_event_thous(event));
}
</script>

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

  position: absolute;
  left: 0;
  top: 0;

  z-index: auto;
}
</style>
