import type { SubjectNode } from "@/types/knowledgeGraph.types";
import type { GraphData } from "@antv/g6";

export class GraphDataManager {
  private graphData: GraphData = {nodes: [], edges: []};
  private nodeIds: Set<string> = new Set();
  private edgeNames: Set<string> = new Set();

  constructor() {}

  public addSubjectNodes(nodes: SubjectNode[]) {
    for (const node of nodes) {
      this.addSubjectNode(node)
    }
  }

  public addSubjectNode(node: SubjectNode) {
    if (!this.nodeIds.has(node.fieldID)) {
      this.graphData.nodes?.push({
        id: node.fieldID,
        nodeId: node.id,
        label: node.name,
      })
      this.nodeIds.add(node.fieldID);
    }
    if (node.children && node.children.length > 0) {
      this.addEdge(node);
      this.addSubjectNodes(node.children)
    }
  }

  private addEdge(node: SubjectNode, deepth: number = 0) {
    if (!node.children || node.children.length <= 0 || deepth > 2) {
      return;
    }
    for (const child of node.children) {
      const key = `${node.fieldID}_${child.fieldID}`;
      if (this.edgeNames.has(key)) {
        continue;
      }
      this.graphData.edges?.push({
        source: node.fieldID,
        target: child.fieldID,
        labelCfg: {
          style: {
            fontSize: 10,
            opacity: 0.5,
          }
        }
      })
      this.edgeNames.add(key);
    }
  }

  public pruge() {
    this.graphData = {nodes: [], edges: []};
    this.nodeIds = new Set();
    this.edgeNames = new Set();
  }

  public getGraphData() {
    return this.graphData;
  }
}
