<template>
  <v-group :config="groupConfig" v-if="groupConfig" ref="shape">
    <v-group :config="initDecMat">
      <v-rect :config="rectConfig" />
      <v-path v-for="config in pathConfigs" :config="config" />
    </v-group>
  </v-group>
</template>

<script lang="ts" setup>
import { defaultStyle, IconData } from "./index.ts";
import { computed, ref, watch } from "vue";
import { getSvgContent, parseSvgContent, SVGParseResult } from "@/utils/resource.ts";
import { Group } from "konva/lib/Group";
import { DC } from "@/deconstruction.js";
import { Transform } from "konva/lib/Util";

const props = defineProps<{ data: IconData; addMode?: boolean }>();
const svg = ref<SVGParseResult | null>(null);
const shape = ref<DC<Group>>();
const data = computed(() => ({ ...defaultStyle, ...props.data }));

defineExpose({
  get shape() {
    return shape.value;
  },
});

watch(
  () => data.value.url,
  async (url) => {
    svg.value = null;
    const svgContent = await getSvgContent(url);
    svg.value = parseSvgContent(svgContent);
  },
  { immediate: true }
);

const pathConfigs = computed(() => {
  if (!svg.value) return [];
  return svg.value.paths.map((path) => ({
    ...path,
    ...data.value,
    zIndex: undefined,
    offset: { x: svg.value!.x, y: svg.value!.y },
  }));
});

const initDecMat = computed(() => {
  if (!svg.value) return null;
  let w = data.value.width;
  let h = data.value.height;
  w = w || svg.value.width || 0;
  h = h || svg.value.height || 0;

  const scale = {
    x: w / svg.value.width,
    y: h / svg.value.height,
  };

  return new Transform()
    .scale(scale.x, scale.y)
    .multiply(new Transform().translate(-svg.value.width / 2, -svg.value.height / 2))
    .decompose();
});

const groupConfig = computed(() => {
  return {
    ...new Transform(data.value.mat).decompose(),
    opacity: props.addMode ? 0.3 : 1,
  };
});

const rectConfig = computed(() => {
  if (!svg.value) return null;
  return {
    fill: data.value.coverFill,
    id: "rep",
    stroke: data.value.coverStroke,
    opacity: data.value.coverOpcatiy,
    strokeWidth: data.value.coverStrokeWidth,
    width: svg.value.width,
    height: svg.value.height,
  };
});
</script>
