use std::{collections::HashMap, error::Error, fmt};
use petgraph::{
dot::{Config, Dot},
graph::NodeIndex,
stable_graph::StableGraph,
visit::{EdgeRef, IntoEdgeReferences},
Undirected,
};
use crate::ForceGraph;
#[derive(Clone, Debug)]
pub enum DotParseError {
IndexNotFound(String),
}
impl fmt::Display for DotParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::IndexNotFound(n) => write!(f, "Index for {n} was not found in the graph"),
}
}
}
impl Error for DotParseError {}
pub fn graph_to_dot<N, E>(graph: &ForceGraph<N, E>) -> Result<String, DotParseError> {
let mut new_graph: StableGraph<String, (), Undirected> = StableGraph::default();
let mut indices: HashMap<String, NodeIndex> = HashMap::new();
for idx in graph.node_indices() {
let node = &graph[idx];
indices.insert(node.name.clone(), new_graph.add_node(node.name.clone()));
}
for edge in graph.edge_references() {
let source = &graph[edge.source()].name;
let target = &graph[edge.target()].name;
let source_idx = match indices.get(source) {
Some(idx) => *idx,
None => return Err(DotParseError::IndexNotFound(source.clone())),
};
let target_idx = match indices.get(target) {
Some(idx) => *idx,
None => return Err(DotParseError::IndexNotFound(target.clone())),
};
new_graph.add_edge(source_idx, target_idx, ());
}
Ok(format!("{:?}", Dot::with_config(&new_graph, &[Config::EdgeNoLabel])).replace("\\\"", ""))
}