import { Graph, Shape } 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';

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',
      router: 'normal',
      // connector: {
      //   name: 'curveConnector',
      // },
      anchor: 'center',
      // connectionPoint: 'boundary',
      allowBlank: false,
      allowLoop: false,
      snap: {
        radius: 20,
      },

      createEdge() {
        return new Shape.Edge({
          tools: [
          ],
          attrs: {
            line: {
              stroke: '#A2B1C3',
              strokeWidth: 2,
              targetMarker: {
                name: 'block',
                width: 12,
                height: 8,
              },
            },
          },
          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, e: KeyboardEvent) {
        console.log('e', e);
        return true;
      },
    })
  );

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

  keyboardEvents(graph);

  return graph;
};
