1use crate::{
2 configuration::GraphConfiguration,
3 link::Link,
4 node::{Node, SharedNode},
5 LinkType,
6};
7use mcai_types::Coordinates;
8use std::collections::HashMap;
9
10pub trait ToGraph {
11 fn to_graph(&self, configuration: GraphConfiguration) -> Graph;
12}
13
14#[derive(Debug)]
15pub struct Graph {
16 nodes: HashMap<u32, SharedNode>,
17 configuration: GraphConfiguration,
18}
19
20impl Graph {
21 pub fn new(configuration: GraphConfiguration) -> Self {
22 Self {
23 nodes: HashMap::new(),
24 configuration,
25 }
26 }
27
28 pub fn nodes(&self) -> HashMap<u32, SharedNode> {
29 self.nodes.clone()
30 }
31
32 pub fn add_node(&mut self, id: u32, coordinates: Coordinates) -> SharedNode {
33 let dimensions = self.configuration.node_configuration().get_dimensions();
34 let node = Node::new(id, coordinates, dimensions).into_rc();
35 self.nodes.insert(id, node.clone());
36 node
37 }
38
39 pub fn get_node(&self, id: u32) -> Option<SharedNode> {
40 self.nodes.get(&id).cloned()
41 }
42
43 pub fn get_links(&self, link_type: LinkType) -> Vec<Link> {
44 self
45 .nodes
46 .iter()
47 .flat_map(|(_, node)| node.borrow().get_links(&link_type))
48 .collect()
49 }
50
51 pub fn move_node(&mut self, id: u32, coordinates: Coordinates) {
52 if let Some(node) = self.nodes.get_mut(&id) {
53 let mut node = node.borrow_mut();
54 node.set_coordinates(coordinates);
55 }
56 }
57
58 pub fn connect(&mut self, src_id: u32, dst_id: u32, link_type: &LinkType) {
59 if let Some(dst_node) = self.get_node(dst_id) {
60 if let Some(src_node) = self.get_node(src_id) {
61 match link_type {
62 LinkType::Parentage => dst_node.borrow_mut().add_parent(src_node),
63 LinkType::Requirement => dst_node.borrow_mut().add_required(src_node),
64 }
65 }
66 }
67 }
68
69 pub fn disconnect(&mut self, src_id: u32, dst_id: u32, link_type: &LinkType) {
70 if let Some(dst_node) = self.get_node(dst_id) {
71 match link_type {
72 LinkType::Parentage => dst_node.borrow_mut().remove_parent(src_id),
73 LinkType::Requirement => dst_node.borrow_mut().remove_required(src_id),
74 }
75 }
76 }
77}