import { useEffect, useRef, useState } from "react";
import { apiAuth } from "./api";
import { GraphCanvas, GraphCanvasRef, GraphEdge, GraphNode, useSelection } from "reagraph";

interface NetworkData {
  nodes: GraphNode[],
  edges: GraphEdge[],
}

export const GraphComponent = () => {
  const [data, setData] = useState({ nodes: [], edges: [] } as NetworkData);
  const [loading, setLoading] = useState(true);

  async function loadData() {
    setLoading(true);
    await apiAuth("analysis/graph_json", null)
      .then(json => json as Promise<NetworkData>).then(json => { setData(json) })
    setLoading(false);
  }

  useEffect(() => { loadData() }, [])

  const graphRef = useRef<GraphCanvasRef | null>(null);

  const { selections, actives, onNodeClick, onCanvasClick } = useSelection({
    ref: graphRef,
    nodes: data.nodes,
    edges: data.edges,
    pathSelectionType: 'out'
  });

  return (
    <GraphCanvas
      draggable
      ref={graphRef}
      nodes={data.nodes}
      edges={data.edges}
      selections={selections}
      actives={actives}
      onCanvasClick={onCanvasClick}
      onNodeClick={onNodeClick}
    />
  );

}

