<template>
  <TempText :data="{ ...atData, ...animation.data }" :ref="(e: any) => shape = e.shape" />
</template>

<script lang="ts" setup>
import TempText from "./temp-text.vue";
import { TextData, style } from "./index.ts";
import { computed, ref, watch, watchEffect } from "vue";

import { DC } from "@/helper/deconstruction";
import { useShapeTransformer } from "../../hook/use-transformer.ts";
import { useAutomaticData } from "../../hook/use-automatic-data.ts";
import { useMouseStyle } from "../../hook/use-mouse-status.ts";
import { useAniamtion } from "../../hook/use-animation.ts";
import { Text } from "konva/lib/shapes/Text";

const props = defineProps<{ data: TextData; addMode?: boolean }>();
const emit = defineEmits<{ (e: "update", value: TextData): void }>();
const shape = ref<DC<Text>>();

const minWidth = computed(() => (props.data.fontSize || 12) * 2);
const transform = useShapeTransformer(shape, {
  enabledAnchors: ["middle-left", "middle-right"],
  flipEnabled: false,
  boundBoxFunc: (oldBox, newBox) => {
    if (Math.abs(newBox.width) < minWidth.value) {
      return oldBox;
    }
    return newBox;
  },
});
const atData = useAutomaticData(() => props.data);

watchEffect(() => {
  const $text = shape.value?.getNode();
  if (!$text) return;
  $text.on("transform", () => {
    const newWidth = Math.max($text.width() * $text.scaleX(), minWidth.value);
    $text.setAttrs({
      width: newWidth,
      scaleX: 1,
      scaleY: 1,
    });
  });
});

watch(transform, (transform, oldTransform) => {
  if (!transform && oldTransform) {
    const $text = shape.value!.getNode();
    emit("update", {
      ...atData.value,
      width: $text.width(),
      mat: $text.getTransform().m,
    });
  }
});

const { currentStyle } = useMouseStyle({ style, shape });
const animation = useAniamtion(currentStyle);
</script>
