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
use std::str::Lines;
use std::vec;

use super::counter::counter_instance::CounterInstance;
use super::counter::counter_types::CounterType;
use super::counter::counters::Counters;

use super::element_text::ElementText;
use super::helpers::*;
use super::parser_helpers::*;

#[derive(Debug)]
pub struct Parser<'a> {
    result: DataCell,
    pub id: usize,
    pub counters: &'a mut Counters,
}

impl<'a> Parser<'a> {
    pub fn new(counters: &'a mut Counters) -> Parser<'a> {
        Self {
            result: DataCell {
                parent_id: 0,
                id: 0,
                cell_type: CellType::Root(Root { children: vec![] }),
            },
            id: 1,
            counters,
        }
    }

    pub fn import_json(json: &String) -> String {
        json.clone()
    }

    fn handle_tag_line(
        &mut self,
        trimmed_line: &str,
        mut curr_el_id: Option<usize>,
        mut is_nested: &bool,
        tag_stack: &mut Vec<TagInfo>,
        indent: usize,
    ) {
        let tag_name = trimmed_line[3..].trim();
        tag_stack_pop(tag_stack, &indent);

        curr_el_id = if let Some(last) = tag_stack.last() {
            Some(last.id)
        } else if *is_nested {
            is_nested = &false;
            curr_el_id
        } else {
            Some(0)
        };

        ElementCell::add_cell(&mut self.result, curr_el_id.unwrap(), self.id, tag_name);

        tag_stack.push(TagInfo {
            id: self.id,
            name: tag_name.to_string(),
            indent,
            is_self_closing: false,
            in_props: true,
        });
        self.id += 1;
    }

    fn props_end(&mut self, trimmed_line: &str, tag_stack: &Vec<TagInfo>) -> bool {
        trimmed_line.is_empty() // end of props
        && tag_stack
            .last()
            .map_or(false, |tag| tag.in_props && !tag.is_self_closing)
    }

    pub fn export_json(
        &mut self,
        elm: &'a str,
        mut curr_el_id: Option<usize>,
        mut is_nested: bool,
    ) -> String {
        let mut tag_stack: Vec<TagInfo> = Vec::new();
        let lines = elm.lines();
        let mut lines_to_skip: u32 = 0;
        let mut text_node = String::new();

        for (index, line) in lines.clone().enumerate() {
            if lines_to_skip > 0 {
                lines_to_skip = lines_to_skip - 1;
                continue;
            }

            let trimmed_line = line.trim_start();
            let indent = get_line_indent(line);

            check_indent_size(indent as isize, line);
            if let Some(last) = tag_stack.last() {
                check_extra_spaces(indent, last.indent, line);
            }

            if trimmed_line.starts_with("|> ") {
                self.handle_tag_line(trimmed_line, curr_el_id, &is_nested, &mut tag_stack, indent);
                continue;
            }
            if self.props_end(trimmed_line, &tag_stack) {
                if let Some(last) = tag_stack.last_mut() {
                    last.in_props = false;
                }
                continue;
            }

            if !trimmed_line.is_empty() {
                tag_stack_pop(&mut tag_stack, &indent);

                curr_el_id = if let Some(last) = tag_stack.last() {
                    Some(last.id)
                } else if is_nested {
                    is_nested = false;
                    curr_el_id
                } else {
                    Some(0)
                };

                let last = tag_stack
                    .last()
                    .expect(&format!("There is no parent tag . at line \n {:?}", line));
                if last.in_props {
                    // tag props
                    let mut prop_line_splits = trimmed_line.split(" ");
                    let counter_type = prop_line_splits.next().unwrap();
                    if CounterType::is_valid(counter_type) {
                        let counter_name =
                            prop_line_splits.next().expect("Counter must have a name");
                        let default_value = prop_line_splits.next();
                        // create new counter
                        self.counters.add_counter(CounterInstance::new(
                            counter_name,
                            counter_type,
                            self.id - 1,
                            default_value,
                        ));
                    }

                    ElementCell::add_attribute(&mut self.result, last.id, trimmed_line);
                    continue;
                }

                let next_line = lines.clone().nth(index + 1);
                let next_line_empty = next_line.is_none()
                    || (next_line.is_some() && next_line.unwrap().trim().is_empty());
                let next_line_is_element =
                    next_line.is_some() && next_line.unwrap().trim_start().starts_with("|> ");
                let next_line_indent = if let Some(next_line) = next_line {
                    Some(get_line_indent(next_line))
                } else {
                    None
                };

                let end_of_attached_element =
                    next_line_indent.is_some_and(|ne| ne > 0 && ne < indent);

                // break if next line is empty
                if next_line_empty
                    || next_line_is_element
                    || indent < tag_stack.last().unwrap().indent
                    || end_of_attached_element
                {
                    text_node = format!(
                        "{}{}{}",
                        text_node,
                        if text_node == "" { "" } else { " " },
                        // if there's one space we keep it
                        if trimmed_line.trim_end().len() + 1 == trimmed_line.len() {
                            trimmed_line
                        } else {
                            trimmed_line.trim_end()
                        },
                    );

                    let mut block = BlockCell::new();
                    let e = ElementText::new(&text_node);
                    let block_children = e.split_text();

                    block_children.iter().for_each(|child| {
                        if let BlockChildType::Text(text) = &child {
                            if text.content != "" {
                                BlockChildType::push_cell(&mut block, child.to_owned());
                            }
                        } else {
                            BlockChildType::push_cell(&mut block, child.to_owned());
                        }
                    });

                    text_node = "".to_string();
                    BlockCell::add_cell(&mut self.result, curr_el_id.unwrap(), self.id, &block);
                    self.id += 1;

                    if end_of_attached_element && tag_stack.len() > 1 {
                        let parent_id = self.get_parent_id(&tag_stack);
                        ElementCell::add_cell(
                            &mut self.result,
                            parent_id.unwrap(),
                            self.id,
                            "Space",
                        );
                        self.id += 1;
                    }

                    continue;
                }

                text_node = format!(
                    "{}{}{}",
                    text_node,
                    if text_node == "" { "" } else { " " },
                    if trimmed_line.trim_end().len() + 1 == trimmed_line.len() {
                        trimmed_line
                    } else {
                        trimmed_line.trim_end()
                    },
                );
                if !text_node.is_empty() {
                    text_node.push_str("\n")
                }
            }
        }
        let res = serde_json::to_string_pretty(&self.result);
        res.unwrap_or("Something Wrong".to_string())
    }

    fn get_parent_id(&self, tag_stack: &Vec<TagInfo>) -> Option<usize> {
        let before_last_index = tag_stack.len().checked_sub(2);
        if before_last_index.is_none() {
            return None;
        }
        let before_last_index = before_last_index.unwrap();
        if let Some(before_last) = tag_stack.get(before_last_index) {
            Some(before_last.id)
        } else {
            None
        }
    }
}