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

use super::ScriptError;

#[derive(Clone, Debug, PartialEq)]
pub struct LinkKVPair((String, String));

impl LinkKVPair {
    /// consume one line of split up words
    pub fn from_words<'a, I>(split: &mut I) -> Result<Self, ScriptError>
    where
        I: Iterator<Item = &'a str>,
    {
        let property = split.next().ok_or(ScriptError::InvalidLink)?.to_owned();
        Ok(LinkKVPair((property, split.collect::<Vec<_>>().join(" "))))
    }

    pub fn from_tuple(pair: (&str, &str)) -> Self {
        Self::from_slices(pair.0, pair.1)
    }

    pub fn from_slices(property: &str, target: &str) -> Self {
        Self((property.to_owned(), target.to_owned()))
    }
}

impl Deref for LinkKVPair {
    type Target = (String, String);
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// One section of link commands...
#[derive(Clone, Debug, PartialEq)]
pub struct Link {
    pub targets: LinkKVPair,
    pub associations: Vec<LinkKVPair>,
    pub negative: bool,
}

/// Target = thing to track
/// Association = thing to link to the target
///
/// In practice:
/// Link NAME <Target>
/// VOX <Association>
impl Link {
    pub fn new(property: &str, target: &str) -> Self {
        let pair = LinkKVPair::from_slices(property, target);
        Self::from_pair(pair)
    }

    pub fn from_pair(from: LinkKVPair) -> Self {
        Self {
            targets: from,
            associations: vec![],
            negative: false,
        }
    }

    pub fn add_association(&mut self, pair: LinkKVPair) {
        self.associations.push(pair);
    }
}

impl fmt::Display for Link {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "{:?}", self.targets)?;

        for link in &self.associations {
            writeln!(f, " -> {:?}", link)?;
        }

        Ok(())
    }
}