<script setup>
import { VueFlow, useVueFlow, MarkerType, ConnectionLineType } from '@vue-flow/core'
import NodeStart from './NodeStart.vue'
import NodeEnd from './NodeEnd.vue'
import NodeCustom from './NodeCustom.vue'
import EdgeCustom from './EdgeCustom.vue'
import { nanoid } from 'nanoid'
import { useLayout } from './useLayout'

const props = defineProps({
  id: {
    type: String,
    default() {
      return nanoid()
    }
  },
  process: { type: Number, default: 1 },
  disabled: { type: Boolean, default: false }
})

const { onConnect, addEdges, fitView, nodes, edges, setNodes, findNode } = useVueFlow(props.id)
onConnect(params => {
  addEdges([
    {
      ...params,
      type: 'custom',
      animated: true,
      markerEnd: MarkerType.ArrowClosed
    }
  ])
})

const { layout } = useLayout(findNode)
async function layoutGraph(direction) {
  if (props.disabled) return
  console.log('layoutGraph', direction)
  setNodes(layout(nodes.value, edges.value, direction))
  nextTick(() => {
    fitView()
  })
}
</script>

<template>
  <VueFlow
    :id="id"
    fit-view-on-init
    :connection-radius="30"
    :nodes-draggable="false"
    :nodes-connectable="false"
    :connection-line-options="{ markerEnd: MarkerType.ArrowClosed, type: ConnectionLineType.Straight }"
    @nodes-initialized="layoutGraph('LR')">
    <template #node-start="props">
      <NodeStart :process="process" :disabled="disabled" v-bind="props" />
    </template>
    <template #node-end="props">
      <NodeEnd :process="process" :disabled="disabled" v-bind="props" />
    </template>
    <template #node-custom="props">
      <NodeCustom :process="process" :disabled="disabled" v-bind="props" @node-remove="layoutGraph('LR')" />
    </template>
    <template #edge-custom="props">
      <EdgeCustom :process="process" :disabled="disabled" v-bind="props" />
    </template>
  </VueFlow>
</template>

<style>
@import '@vue-flow/core/dist/style.css';
@import '@vue-flow/core/dist/theme-default.css';
</style>
