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
use std::collections::btree_map::Values;
use crate::ast::node::Node;
use crate::format::command::Command;
use crate::format::flusher::Flusher;
use crate::format::Preferences;
use crate::traits::write::Write;

pub struct Writer<'a> {
    pub(super) preferences: Preferences,
    pub(super) commands: Vec<Command<'a>>,
    can_write: bool,
}

impl Default for Writer<'_> {
    fn default() -> Self {
        Self::new(Preferences::default())
    }
}

impl<'a> Writer<'a> {

    pub fn new(preferences: Preferences) -> Self {
        Self {
            preferences,
            commands: vec![],
            can_write: true,
        }
    }

    pub fn write_children(&mut self, node: &'a dyn Write, children: Values<'a, usize, Node>) {
        if !self.can_write {
            panic!("writer can only write only once in one call");
        }
        let mut writer: Writer = Self::new(self.preferences);
        for c in children {
            c.write(&mut writer);
            writer.can_write = true;
        }
        self.commands.push(Command::branch(node, writer.commands));
        self.can_write = false;
    }

    pub fn write_content(&mut self, node: &'a dyn Write, content: &'a str) {
        if !self.can_write {
            panic!("writer can only write only once in one call");
        }
        self.commands.push(Command::leaf(node, vec![content.as_ref()]));
        self.can_write = false;
    }

    pub fn write_contents(&mut self, node: &'a dyn Write, contents: Vec<&'a str>) {
        if !self.can_write {
            panic!("writer can only write only once in one call");
        }
        self.commands.push(Command::leaf(node, contents));
        self.can_write = false;
    }

    pub fn flush(&self) -> String {
        let mut flusher = Flusher::new_from_beginning(&self.commands, self.preferences);
        flusher.flush()
    }
}