<script lang="ts" setup>
import { CSSProperties } from 'vue'
import { invoke } from '@vueuse/core'
import { ConnectionLineType } from '../../types'
import { useStore } from '../../composables'
import Edge from '../../components/Edges/Edge.vue'
import ConnectionLine from '../../components/ConnectionLine/ConnectionLine.vue'
import MarkerDefinitions from './MarkerDefinitions.vue'

interface EdgeRendererProps {
  connectionLineType?: ConnectionLineType
  connectionLineStyle?: CSSProperties
  arrowHeadColor?: string
  markerEndId?: string
  edgeUpdaterRadius?: number
}

const props = withDefaults(defineProps<EdgeRendererProps>(), {
  arrowHeadColor: '#b1b1b7',
  connectionLineType: ConnectionLineType.Bezier,
  edgeUpdaterRadius: 10,
})

const store = useStore()

invoke(async () => {
  await until(store.getNodes).toMatch((y) => y && y.length > 0)
  await until(store.transform).toMatch(([x, y, z]) => !isNaN(x) && x !== 0 && !isNaN(y) && y !== 0 && isNaN(z) && z !== 1)
})

const sourceNode = computed(() => store.nodes.find((n) => n.id === store.connectionNodeId))
const connectionLineVisible = computed(
  () => !!(store.nodesConnectable && sourceNode.value && store.connectionNodeId && store.connectionHandleType),
)
const dimensions = computed(() => store.dimensions)
const transform = computed(() => `translate(${store.transform[0]},${store.transform[1]}) scale(${store.transform[2]})`)
</script>
<template>
  <svg :width="dimensions.width" :height="dimensions.height" class="vue-flow__edges">
    <MarkerDefinitions :color="props.arrowHeadColor" />
    <g :transform="transform">
      <Edge
        v-for="edge of store.getEdges"
        :key="edge.id"
        :edge="edge"
        :marker-end-id="props.markerEndId"
        :edge-updater-radius="props.edgeUpdaterRadius"
      >
        <template #default="edgeProps">
          <slot :name="`edge-${edge.type}`" v-bind="edgeProps"></slot>
        </template>
      </Edge>
      <ConnectionLine
        v-if="connectionLineVisible && sourceNode"
        :source-node="sourceNode"
        :connection-line-style="props.connectionLineStyle"
        :connection-line-type="props.connectionLineType"
      >
        <template #default="customConnectionLineProps">
          <slot name="custom-connection-line" v-bind="customConnectionLineProps"></slot>
        </template>
      </ConnectionLine>
    </g>
  </svg>
</template>
