1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//! Actors graph

use std::{
    collections::{hash_map::DefaultHasher, HashMap},
    fs::File,
    hash::{Hash, Hasher},
    io::Write,
    path::Path,
};

use crate::{model::PlainModel, trim};
mod render;
pub use render::{Render, RenderError};

/// [Model](crate::model::Model) network mapping
///
/// The structure is used to build a [Graphviz](https://www.graphviz.org/) diagram of a [Model](crate::model::Model).
/// A new [Graph] is created with `Model::graph()`.
///
/// The model flow chart is written to a SVG image with `<cmd> -Gstart=rand -Tsvg -O filename.dot`,
/// where `<cmd>` is set to the value of the environment variable `FLOWCHART` if given, `neato` otherwise
#[derive(Debug, Hash, Default, Clone)]
pub struct Graph {
    pub(crate) name: String,
    actors: PlainModel,
}
impl Graph {
    pub fn new(name: String, actors: impl Into<PlainModel>) -> Self {
        let mut hasher = DefaultHasher::new();
        let mut actors: PlainModel = actors.into();
        actors.iter_mut().for_each(|actor| {
            // actor.client = actor
            //     .client
            //     .replace("::Controller", "")
            //     .split('<')
            //     .next()
            //     .unwrap()
            //     .split("::")
            //     .last()
            //     .unwrap()
            //     .to_string();
            actor.client = trim(&actor.client);
            actor.hash(&mut hasher);
            actor.hash = hasher.finish();
        });
        Self { name, actors }
    }
    /// Returns the diagram in the [Graphviz](https://www.graphviz.org/) dot language
    pub fn to_string(&self) -> String {
        let mut lookup: HashMap<usize, usize> = HashMap::new();
        let mut colors = (1usize..=8).cycle();
        let outputs: Vec<_> = self
            .actors
            .iter()
            .filter_map(|actor| {
                actor.outputs.as_ref().map(|outputs| {
                    outputs
                        .iter()
                        .map(|output| {
                            let color = lookup
                                .entry(actor.outputs_rate)
                                .or_insert_with(|| colors.next().unwrap());
                            output.as_formatted_output(actor.hash, *color)
                        })
                        .collect::<Vec<String>>()
                })
            })
            .flatten()
            .collect();
        let inputs: Vec<_> = self
            .actors
            .iter()
            .filter_map(|actor| {
                actor.inputs.as_ref().map(|inputs| {
                    inputs
                        .iter()
                        .map(|input| {
                            let color = lookup
                                .entry(actor.inputs_rate)
                                .or_insert_with(|| colors.next().unwrap());
                            input.as_formatted_input(actor.hash, *color)
                        })
                        .collect::<Vec<String>>()
                })
            })
            .flatten()
            .collect();
        format!(
            r#"
digraph  G {{
  overlap = scale;
  splines = true;
  bgcolor = gray24;
  {{node [shape=box, width=1.5, style="rounded,filled", fillcolor=lightgray]; {};}}
  node [shape=point, fillcolor=gray24, color=lightgray];

  /* Outputs */
{{
  edge [arrowhead=none,colorscheme=dark28];
  {}
}}
  /* Inputs */
{{
  edge [arrowhead=vee,fontsize=9, fontcolor=lightgray, labelfloat=true,colorscheme=dark28]
  {}
}}
}}
"#,
            self.actors
                .iter()
                .map(|actor| if let Some(image) = actor.image.as_ref() {
                    format!(
                        r#"{} [label="{}", labelloc=t, image="{}"]"#,
                        actor.hash, actor.client, image
                    )
                } else {
                    format!(r#"{} [label="{}"]"#, actor.hash, actor.client)
                })
                .collect::<Vec<String>>()
                .join("; "),
            outputs.join("\n"),
            inputs.join("\n"),
        )
    }
    /// Writes the output of [Graph::to_string()] to a file
    pub fn to_dot<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
        let mut file = File::create(path)?;
        write!(&mut file, "{}", self.to_string())?;
        Ok(())
    }
    pub fn walk(&self) -> Render {
        let mut render = Render::from(self);
        for actor in &self.actors {
            if let Some(graph) = actor.graph.as_ref() {
                render
                    .child
                    .get_or_insert(Vec::new())
                    .push(Box::new(graph.walk()));
            }
        }
        log::debug!("{:}", render);
        render
    }
}

#[cfg(test)]
mod tests {
    use super::trim;

    #[test]
    fn parse_client_name() {
        let a = trim("print");
        dbg!(&a);
        let a = trim("a::b::print");
        dbg!(a);
        let a = trim("a::b::print<w::W,q::s::C>");
        dbg!(a);
        // let a = trim("a::b::print<w::W>");
    }
}