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
use std::fmt;

use super::{parse_agent_id, parse_agent_role, parse_plug_name};

/// Role, IDs, OutputPlugs
pub struct AgentTree {
    pub role: String,
    pub ids: Vec<String>,
    pub output_plugs: Vec<String>,
}

impl AgentTree {
    pub fn new(role: &str, topics: &[String]) -> AgentTree {
        let topics_this_agent = topics.iter().filter_map(|topic| {
            if let Some(role_part) = parse_agent_role(topic.as_str()) {
                if role_part == role {
                    Some(String::from(topic))
                } else {
                    None
                }
            } else {
                None
            }
        });

        let ids = topics_this_agent
            .clone()
            .fold(Vec::new(), |mut acc, topic| {
                if let Some(id) = parse_agent_id(&topic) {
                    if !acc.iter().any(|x| x == id) {
                        acc.push(String::from(id))
                    }
                }
                acc
            });

        let output_plugs = topics_this_agent
            .clone()
            .fold(Vec::new(), |mut acc, topic| {
                if let Some(p) = parse_plug_name(&topic) {
                    acc.push(String::from(p));
                }
                acc
            });

        AgentTree {
            role: role.into(),
            ids: ids.to_vec(),
            output_plugs: output_plugs.to_vec(),
        }
    }
}

impl fmt::Display for AgentTree {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let Self {
            role,
            ids,
            output_plugs,
        } = self;
        let ids_list = ids
            .iter()
            .fold(String::from(""), |acc, x| format!("{}\n    - {}", acc, x));
        let output_plugs_list = output_plugs.iter().fold(String::from(""), |acc, x| {
            format!("{}\n        - {}", acc, x)
        });
        write!(f, "\n{}\n {}\n {}\n", role, ids_list, output_plugs_list)
    }
}