<template>
  <v-circle :config="{ ...style, ...position }" ref="circle" />
</template>

<script lang="ts" setup>
import { Pos } from "@/utils/math.ts";
import { themeColor } from "@/constant/help-style.ts";
import { computed, ref, watch } from "vue";
import { DC } from "@/deconstruction";
import { Circle } from "konva/lib/shapes/Circle";
import { useShapeDrag } from "@/core/hook/use-transformer.ts";
import { getMouseColors } from "@/utils/colors";
import { useGlobalSnapInfos, useSnap } from "@/core/hook/use-snap";
import { generateSnapInfos } from "../util";
import { ComponentSnapInfo } from "..";

const props = defineProps<{
  position: Pos;
  id?: any;
  color?: string;
  size?: number;
  shapeId?: string;
  getSelfSnapInfos?: (point: Pos) => ComponentSnapInfo[];
}>();
const emit = defineEmits<{
  (e: "update:position", position: Pos): void;
  (e: "dragend"): void;
  (e: "dragstart"): void;
}>();

const style = computed(() => {
  const color = getMouseColors(props.color || themeColor);
  const size = props.size || 5;
  return {
    radius: size / 2,
    fill: color.disable,
    stroke: color.press,
    strokeWidth: size / 4,
  };
});

const snapInfos = useGlobalSnapInfos();
const refSnapInfos = computed(() => {
  if (!props.shapeId) {
    return snapInfos.value;
  } else {
    return snapInfos.value.filter((p) => !("id" in p) || p.id !== props.shapeId);
  }
});
const snap = useSnap(refSnapInfos);
const circle = ref<DC<Circle>>();
const offset = useShapeDrag(circle);
let init: Pos;
watch(offset, (offset, oldOffsert) => {
  snap.clear();
  if (!oldOffsert) {
    init = { ...props.position };
    emit("dragstart");
  }
  if (offset) {
    const point = {
      x: init.x + offset.x,
      y: init.y + offset.y,
    };
    const refSnapInfos = props.getSelfSnapInfos
      ? props.getSelfSnapInfos(point)
      : generateSnapInfos([point], true, true);
    const transform = snap.move(refSnapInfos);
    emit("update:position", transform ? transform.point(point) : point);
  } else {
    emit("dragend");
  }
});
</script>
