import { Edge, Graph } from '@antv/x6';
import { Selection } from '@antv/x6-plugin-selection';
import { Snapline } from '@antv/x6-plugin-snapline';
import { Keyboard } from '@antv/x6-plugin-keyboard';
import { Clipboard } from '@antv/x6-plugin-clipboard';
import { History } from '@antv/x6-plugin-history';
import { keyboardEvents } from './keyboard';
import { stencilRegister } from './stencil';
import { initNodeEvents } from './nodeEvents';
import { v4 as uuidv4 } from 'uuid';

export const FLOW_CREATE_ID = 'flow-create-content';

export const initGraph = async () => {
  const graph = new Graph({
    panning: {
      enabled: false,
    },
    container: document.getElementById(FLOW_CREATE_ID) as HTMLElement,
    autoResize: true,
    //	画布的最小最大缩放级别
    scaling: { min: 0.5, max: 3 },
    grid: true,
    // width: 800,
    // height: 800,
    background: {
      color: '#F2F7FA',
    },
    // interacting: {
    //   magnetConnectable: true,
    //   edgeMovable: true,
    //   vertexMovable: true,
    // },
    connecting: {
      connector: { name: 'smooth' },
      connectionPoint: 'anchor',
      allowBlank: false,
      snap: { radius: 20 },
      allowEdge: false,
      allowLoop: false,
      highlight: true,
      createEdge(): Edge {
        return graph.createEdge({
          shape: 'agent-edge',
          id: 'uuid-edge-' + uuidv4(),
          // 将线至于底层，防止线将连接桩遮挡
          zIndex: 0,
        });
      },
      validateConnection({ targetMagnet }) {
        return !!targetMagnet;
      },
    },
  });

  await stencilRegister(graph);

  initNodeEvents(graph);

  graph.use(
    new Snapline({
      enabled: true,
      sharp: true,
    })
  );

  graph.use(
    new Clipboard({
      enabled: true,
      useLocalStorage: true,
    })
  );

  graph.use(
    new Selection({
      enabled: true,
      multiple: true,
      rubberband: true,
      movable: true,
      showNodeSelectionBox: true,
    })
  );

  graph.use(
    new Keyboard({
      enabled: true,
      global: true,
      guard(this: Graph) {
        return true;
      },
    })
  );

  graph.use(
    new History({
      enabled: true,
    })
  );

  keyboardEvents(graph);

  return graph;
};
