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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! A context defines methods to retrieve variable values and call functions for literals in an expression tree.
//! If mutable, it also allows to assign to variables.
//!
//! This crate implements two basic variants, the `EmptyContext`, that returns `None` for each identifier and cannot be manipulated, and the `HashMapContext`, that stores its mappings in hash maps.
//! The HashMapContext is type-safe and returns an error if the user tries to assign a value of a different type than before to an identifier.

use std::{
    collections::BTreeMap,
    fmt::Display,
    fs,
    io::{Read, Write},
    process::Command,
};

use crate::{
    container,
    function::Function,
    time,
    value::{value_type::ValueType, Value},
    EvalexprError, EvalexprResult,
};

mod predefined;

/// An immutable context.
pub trait Context {
    /// Returns the value that is linked to the given identifier.
    fn get_value(&self, identifier: &str) -> Option<&Value>;

    /// Calls the function that is linked to the given identifier with the given argument.
    /// If no function with the given identifier is found, this method returns `EvalexprError::FunctionIdentifierNotFound`.
    fn call_function(&self, identifier: &str, argument: &Value) -> EvalexprResult<Value>;
}

/// A context that allows to assign to variables.
pub trait ContextWithMutableVariables: Context {
    /// Sets the variable with the given identifier to the given value.
    fn set_value(&mut self, _identifier: &str, _value: Value) -> EvalexprResult<()> {
        Err(EvalexprError::ContextNotMutable)
    }
}

/// A context that allows to assign to function identifiers.
pub trait ContextWithMutableFunctions: Context {
    /// Sets the function with the given identifier to the given function.
    fn set_function(&mut self, _identifier: String, _function: Function) -> EvalexprResult<()> {
        Err(EvalexprError::ContextNotMutable)
    }
}

/// A context that stores its mappings in hash maps.
#[derive(Clone, Debug, Default)]
pub struct VariableMap {
    variables: BTreeMap<String, Value>,
}

impl Display for VariableMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "(")?;

        for (key, value) in &self.variables {
            write!(f, " {} = {};", key, value)?;
        }

        write!(f, " )")
    }
}

impl PartialEq for VariableMap {
    fn eq(&self, other: &Self) -> bool {
        if self.variables.len() != other.variables.len() {
            return false;
        }

        for variable in &self.variables {
            for other in &other.variables {
                if variable != other {
                    return false;
                }
            }
        }

        true
    }
}

impl VariableMap {
    /// Create a new instace.
    pub fn new() -> Self {
        Default::default()
    }
}

impl Context for VariableMap {
    fn get_value(&self, identifier: &str) -> Option<&Value> {
        let split = identifier.split_once(".");
        if let Some((map_name, next_identifier)) = split {
            let value = self.variables.get(map_name)?;
            if let Value::Map(map) = value {
                map.get_value(next_identifier)
            } else {
                None
            }
        } else {
            self.variables.get(identifier)
        }
    }

    fn call_function(&self, identifier: &str, argument: &Value) -> EvalexprResult<Value> {
        call_whale_function(identifier, argument)
    }
}

impl ContextWithMutableVariables for VariableMap {
    fn set_value(&mut self, identifier: &str, value: Value) -> EvalexprResult<()> {
        let split = identifier.split_once(".");

        if let Some((map_name, next_identifier)) = split {
            if let Some(map_value) = self.variables.get_mut(map_name) {
                if let Value::Map(map) = map_value {
                    map.set_value(next_identifier, value)
                } else {
                    return Err(EvalexprError::ExpectedMap {
                        actual: map_value.clone(),
                    });
                }
            } else {
                let mut new_map = VariableMap {
                    variables: BTreeMap::new(),
                };

                new_map.set_value(next_identifier, value)?;
                self.variables
                    .insert(map_name.to_string(), Value::Map(new_map));

                Ok(())
            }
        } else if self.variables.contains_key(identifier) {
            Err(EvalexprError::ExpectedMap {
                actual: value.clone(),
            })
        } else {
            self.variables.insert(identifier.to_string(), value);

            Ok(())
        }
    }
}

impl ContextWithMutableFunctions for VariableMap {
    fn set_function(&mut self, identifier: String, function: Function) -> EvalexprResult<()> {
        todo!()
    }
}

/// This macro provides a convenient syntax for creating a static context.
///
/// # Examples
///
/// ```rust
/// use evalexpr::*;
///
/// let ctx = evalexpr::context_map! {
///     "x" => 8,
///     "f" => Function::new(|_| Ok(42.into()))
/// }.unwrap(); // Do proper error handling here
///
/// assert_eq!(eval_with_context("x + f()", &ctx), Ok(50.into()));
/// ```
#[macro_export]
macro_rules! context_map {
    // Termination (allow missing comma at the end of the argument list)
    ( ($ctx:expr) $k:expr => Function::new($($v:tt)*) ) =>
        { $crate::context_map!(($ctx) $k => Function::new($($v)*),) };
    ( ($ctx:expr) $k:expr => $v:expr ) =>
        { $crate::context_map!(($ctx) $k => $v,)  };
    // Termination
    ( ($ctx:expr) ) => { Ok(()) };

    // The user has to specify a literal 'Function::new' in order to create a function
    ( ($ctx:expr) $k:expr => Function::new($($v:tt)*) , $($tt:tt)*) => {{
        $crate::ContextWithMutableFunctions::set_function($ctx, $k.into(), $crate::Function::new($($v)*))
            .and($crate::context_map!(($ctx) $($tt)*))
    }};
    // add a value, and chain the eventual error with the ones in the next values
    ( ($ctx:expr) $k:expr => $v:expr , $($tt:tt)*) => {{
        $crate::ContextWithMutableVariables::set_value($ctx, $k.into(), $v.into())
            .and($crate::context_map!(($ctx) $($tt)*))
    }};

    // Create a context, then recurse to add the values in it
    ( $($tt:tt)* ) => {{
        let mut context = $crate::VariableMap::new();
        $crate::context_map!((&mut context) $($tt)*)
            .map(|_| context)
    }};
}

fn call_whale_function(identifier: &str, argument: &Value) -> Result<Value, EvalexprError> {
    match identifier {
        "container::image::build" => container::image::build(argument),
        "container::image::list" => container::image::list(argument),
        "container::list" => container::list(argument),
        "container::run" => container::run(argument),
        "convert" => todo!(),
        "dir::create" => {
            let path = argument.as_string()?;
            std::fs::create_dir_all(path).unwrap();

            Ok(Value::Empty)
        },
        "dir::read" => {
            let path = argument.as_string()?;
            let files = std::fs::read_dir(path)
                .unwrap()
                .map(|entry| entry.unwrap().file_name().into_string().unwrap_or_default())
                .collect();

            Ok(Value::String(files))
        },
        "dir::remove" => {
            let path = argument.as_string()?;
            std::fs::remove_file(path).unwrap();

            Ok(Value::Empty)
        },
        "dir::trash" => todo!(),
        "dnf::copr" => {
            let repo_name = if let Ok(string) = argument.as_string() {
                string
            } else if let Ok(tuple) = argument.as_tuple() {
                let mut repos = String::new();

                for repo in tuple {
                    let repo = repo.as_string()?;

                    repos.push_str(&repo);
                    repos.push(' ');
                }

                repos
            } else {
                return Err(EvalexprError::ExpectedString {
                    actual: argument.clone(),
                });
            };
            let script = format!("dnf -y copr enable {repo_name}");

            Command::new("fish")
                .arg("-c")
                .arg(script)
                .spawn()
                .unwrap()
                .wait()
                .unwrap();

            Ok(Value::Empty)
        },
        "dnf::packages" => {
            let tuple = argument.as_tuple()?;
            let mut packages = String::new();

            for package in tuple {
                let package = package.as_string()?;

                packages.push_str(&package);
                packages.push(' ');
            }
            let script = format!("dnf -y install {packages}");

            Command::new("fish")
                .arg("-c")
                .arg(script)
                .spawn()
                .unwrap()
                .wait()
                .unwrap();

            Ok(Value::Empty)
        },
        "dnf::repos" => {
            let tuple = argument.as_tuple()?;
            let mut repos = String::new();

            for repo in tuple {
                let repo = repo.as_string()?;

                repos.push_str(&repo);
                repos.push(' ');
            }
            let script = format!("dnf -y config-manager --add-repo {repos}");

            Command::new("fish")
                .arg("-c")
                .arg(script)
                .spawn()
                .unwrap()
                .wait()
                .unwrap();

            Ok(Value::Empty)
        },
        "dnf::upgrade" => {
            Command::new("fish")
                .arg("-c")
                .arg("dnf -y upgrade")
                .spawn()
                .unwrap()
                .wait()
                .unwrap();

            Ok(Value::Empty)
        },
        "file::append" => {
            let strings = argument.as_tuple()?;

            if strings.len() < 2 {
                return Err(EvalexprError::WrongFunctionArgumentAmount {
                    expected: 2,
                    actual: strings.len(),
                });
            }

            let path = strings.first().unwrap().as_string()?;
            let mut file = std::fs::OpenOptions::new().append(true).open(path).unwrap();

            for content in &strings[1..] {
                let content = content.as_string()?;

                file.write_all(content.as_bytes()).unwrap();
            }

            Ok(Value::Empty)
        },
        "file::metadata" => {
            let path = argument.as_string()?;
            let metadata = std::fs::metadata(path).unwrap();

            Ok(Value::String(format!("{:#?}", metadata)))
        },
        "file::move" => {
            let mut paths = argument.as_tuple()?;

            if paths.len() != 2 {
                return Err(EvalexprError::WrongFunctionArgumentAmount {
                    expected: 2,
                    actual: paths.len(),
                });
            }

            let to = paths.pop().unwrap().as_string()?;
            let from = paths.pop().unwrap().as_string()?;

            std::fs::copy(&from, to)
                .and_then(|_| std::fs::remove_file(from))
                .unwrap();

            Ok(Value::Empty)
        },
        "file::read" => {
            let path = argument.as_string()?;
            let mut contents = String::new();

            fs::OpenOptions::new()
                .read(true)
                .create(false)
                .open(&path)
                .unwrap()
                .read_to_string(&mut contents)
                .unwrap();

            Ok(Value::String(contents))
        },
        "file::remove" => {
            let path = argument.as_string()?;
            std::fs::remove_file(path).unwrap();

            Ok(Value::Empty)
        },
        "file::trash" => todo!(),
        "file::write" => {
            let strings = argument.as_tuple()?;

            if strings.len() < 2 {
                return Err(EvalexprError::WrongFunctionArgumentAmount {
                    expected: 2,
                    actual: strings.len(),
                });
            }

            let path = strings.first().unwrap().as_string()?;
            let mut file = fs::OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(path)
                .unwrap();

            for content in &strings[1..] {
                let content = content.as_string()?;

                file.write_all(content.as_bytes()).unwrap();
            }

            Ok(Value::Empty)
        },
        "gui::window" => todo!(),
        "gui" => todo!(),
        "map" => todo!(),
        "network::download" => todo!(),
        "network::hostname" => todo!(),
        "network::scan" => todo!(),
        "os::status" => {
            Command::new("fish")
                .arg("-c")
                .arg("rpm-ostree status")
                .spawn()
                .unwrap()
                .wait()
                .unwrap();
            Ok(Value::Empty)
        },
        "os::upgrade" => {
            Command::new("fish")
                .arg("-c")
                .arg("rpm-ostree upgrade")
                .spawn()
                .unwrap()
                .wait()
                .unwrap();
            Ok(Value::Empty)
        },
        "output" => {
            println!("{}", argument);
            Ok(Value::Empty)
        },
        "random::boolean" => todo!(),
        "random::float" => todo!(),
        "random::int" => todo!(),
        "random::string" => todo!(),
        "run::async" => todo!(),
        "run::sync" => todo!(),
        "run" => todo!(),
        "rust::packages" => todo!(),
        "rust::toolchain" => todo!(),
        "shell::bash" => todo!(),
        "shell::fish" => todo!(),
        "shell::nushell" => todo!(),
        "shell::sh" => todo!(),
        "shell::zsh" => todo!(),
        "system::info" => todo!(),
        "system::monitor" => todo!(),
        "system::processes" => todo!(),
        "system::services" => todo!(),
        "system::users" => todo!(),
        "time::now" => time::now(),
        "time::today" => time::today(),
        "time::tomorrow" => time::tomorrow(),
        "time" => time::now(),
        "toolbox::create" => todo!(),
        "toolbox::enter" => todo!(),
        "toolbox::image::build" => todo!(),
        "toolbox::image::list" => todo!(),
        "toolbox::list" => todo!(),
        "trash" => todo!(),
        "wait" => todo!(),
        "watch" => todo!(),
        _ => Err(EvalexprError::FunctionIdentifierNotFound(
            identifier.to_string(),
        )),
    }
}