import {
  createCmdConfig,
  DisposableCollection,
  uuidv4,
  NsGraphCmd,
  XFlowGraphCommands,
  IApplication,
  IGraphPipelineCommand,
  MODELS,
  NsGraph,
} from '@antv/xflow';
// import { MockApi } from './service';

export const useCmdConfig = props => {
  const cmdConfig = createCmdConfig(config => {
    config.setRegisterHookFn(hooks => {
      const list = [
        hooks.addNode.registerHook({
          name: 'set node config',
          handler: async args => {
            args.nodeConfig.ports?.items.forEach(item => {
              item.id = item.id || uuidv4().substring(0, 8);
            });
            args.nodeConfig = {
              ...args.nodeConfig,
              // ports
              id: args.nodeConfig.id || `${uuidv4().substring(0, 8)}`,
            };
          },
        }),
        // hooks.addEdge.registerHook({
        //   name: 'addEdge',
        //   handler: async args => {
        //     args.edgeConfig = {
        //       ...args.edgeConfig,
        //       id: `${uuidv4().substring(0, 8)}`,
        //     };
        //   },
        // }),
        hooks.selectNode.registerHook({
          name: 'selectNode',
          handler: async args => {
            console.log('select node:', args);
            props.onSelectNode?.(args);
          },
        }),
        // hooks.updateNode.registerHook({
        //   name: 'updateNode',
        //   handler: async args => {
        //     const { nodeConfig } = args;
        //     props.onUpdate?.(nodeConfig);
        //   },
        // }),
      ];
      const toDispose = new DisposableCollection();
      toDispose.pushAll(list);
      return toDispose;
    });
  });

  return cmdConfig();
};

/** 查询图的节点和边的数据 */
export const initGraphCmds = (app: IApplication, graphData: NsGraph.IGraphData) => {
  if (!app) return;
  app.executeCommandPipeline([
    /** 1. 从服务端获取数据 */
    // {
    //   commandId: XFlowGraphCommands.LOAD_DATA.id,
    //   getCommandOption: async () => {
    //     return {
    //       args: {
    //         loadDataService: MockApi.loadGraphData,
    //       },
    //     };
    //   },
    // } as IGraphPipelineCommand<NsGraphCmd.GraphLoadData.IArgs>,
    /** 3. 画布内容渲染 */
    {
      commandId: XFlowGraphCommands.GRAPH_RENDER.id,
      getCommandOption: async () => {
        return {
          args: {
            graphData,
          },
        };
      },
    } as IGraphPipelineCommand<NsGraphCmd.GraphRender.IArgs>,
    /** 4. 缩放画布 */
    {
      commandId: XFlowGraphCommands.GRAPH_ZOOM.id,
      getCommandOption: async () => {
        return {
          args: { factor: 'fit', zoomOptions: { maxScale: 1 } },
        };
      },
    } as IGraphPipelineCommand<NsGraphCmd.GraphZoom.IArgs>,
  ]);
};
