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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use std::fs;
use std::path::Path;
use std::collections::HashSet;

pub mod lexer;
pub mod parser;

pub use lexer::{Lexer, Symbol, LexerError, LexerOptions};
pub use parser::{Parser, Type, Expression, ParserError};

#[derive(Debug, Clone, Default)]
pub struct Config(HashSet<Expression>);

impl Config {
    pub fn parse(path: impl AsRef<Path>, options: LexerOptions) -> Result<Self, Box<dyn std::error::Error>> {
        let contents = fs::read(path)?;

        let mut lexer = lexer::Lexer::new(contents, options);
        let symbols = lexer.lex()?;

        let mut parser = parser::Parser::new(symbols);
        let config = parser.parse()?;

        Ok(config)
    }

    pub fn set(&mut self, expression: Expression) {
        if let Type::Null = expression.value {
            self.0.remove(&expression);
        } else {
            self.0.insert(expression);
        }
    }

    pub fn get(&self, key: impl AsRef<str>) -> Option<&Type> {
        let namespaces = key.as_ref().split('.');

        let mut value: Option<&Type> = None;
        for key in namespaces {
            if let Some(inner) = value {
                if let Type::Dict(dict) = inner {
                    value = dict.0.get(&Expression::new(key, Type::Null)).map(|expr| &expr.value);
                } else {
                    return None;
                }
            } else {
                value = self.0.get(&Expression::new(key, Type::Null)).map(|expr| &expr.value);
            }
        } 

        value
    }

    pub fn get_integer(&self, key: impl AsRef<str>) -> Option<&i64> {
        if let Type::Integer(inner) = self.get(key)? {
            Some(inner)
        } else {
            None
        }
    }

    pub fn get_float(&self, key: impl AsRef<str>) -> Option<&f64> {
        if let Type::Float(inner) = self.get(key)? {
            Some(inner)
        } else {
            None
        }
    }

    pub fn get_boolean(&self, key: impl AsRef<str>) -> Option<&bool> {
        if let Type::Boolean(inner) = self.get(key)? {
            Some(inner)
        } else {
            None
        }
    }

    pub fn get_string(&self, key: impl AsRef<str>) -> Option<&String> {
        if let Type::String(inner) = self.get(key)? {
            Some(inner)
        } else {
            None
        }
    }

    pub fn get_array(&self, key: impl AsRef<str>) -> Option<&Vec<Type>> {
        if let Type::Array(inner) = self.get(key)? {
            Some(inner)
        } else {
            None
        }
    }

    pub fn get_dict(&self, key: impl AsRef<str>) -> Option<&Config> {
        if let Type::Dict(inner) = self.get(key)? {
            Some(inner)
        } else {
            None
        }
    }
}

impl IntoIterator for Config {
    type Item = Expression;
    type IntoIter = <HashSet<Expression> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl std::fmt::Display for Type {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use Type::*;
        match self {
            Null => write!(f, "\x1b[34mnull\x1b[m")?,
            Integer(number) => write!(f, "\x1b[33m{}\x1b[m", number)?,
            Float(number) => write!(f, "\x1b[33m{}\x1b[m", number)?,
            String(string) => write!(f, "\x1b[32m{:?}\x1b[m", string)?,
            Boolean(bool) => write!(f, "\x1b[31m{}\x1b[m", bool)?,
            Array(array) => {
                write!(f, "[")?;

                for (i, entry) in array.iter().enumerate() {
                    write!(f, "{entry}")?;

                    if i != array.len() - 1 {
                        write!(f, ", ")?;
                    }
                }

                write!(f, "]")?;
            }
            Dict(dict) => {
                writeln!(f, "{{")?;

                for entry in &dict.0 {
                    writeln!(f, "  {}", format!("{entry}").replace('\n', "\n  "))?;
                }

                write!(f, "}}")?;
            }
        };

        Ok(())
    }
}

impl std::fmt::Display for Expression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} = {}", self.key, self.value)
    }
}

impl std::fmt::Display for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Config {{")?;
        
        for entry in &self.0 {
            writeln!(f, "  {}", format!("{entry}").replace('\n', "\n  "))?;
        }

        write!(f, "}}")?;

        Ok(())
    }
}

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

    #[test]
    fn config_get() {
        let mut config = Config::default();

        let mut employees = Config::default();
        employees.set(Expression::new("employee-1", Type::String("John Doe".into())));

        let mut clusters = Config::default();
        clusters.set(Expression::new("server-1", Type::String("127.0.0.1".into())));

        let mut instances = Config::default();
        instances.set(Expression::new("heaven-1", Type::Dict(clusters)));

        config.set(Expression::new("cities", Type::Array(Vec::new())));
        config.set(Expression::new("employees", Type::Dict(employees)));
        config.set(Expression::new("clusters", Type::Dict(instances)));

        assert!(config.get("products").is_none());

        assert!(config.get("cities").is_some());

        assert!(config.get("employees").is_some());
        assert!(config.get("employees.employee-1").is_some());
        assert!(config.get("employees.employee-2").is_none());

        assert!(config.get("clusters").is_some());
        assert!(config.get("clusters.heaven-1").is_some());
        assert!(config.get("clusters.heaven-1.server-1").is_some());
        assert!(config.get("clusters.heaven-1.server-2").is_none());
        assert!(config.get("clusters.hell-1").is_none());
        assert!(config.get("clusters.hell-1.devin").is_none());
    }
}