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
use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::rc::Rc;
use std::vec::Vec;
use std::{borrow::BorrowMut, cell::RefCell};
use tui::layout::{Alignment, Rect};
use tui::style::{Color, Style};
use xml::reader::{EventReader, XmlEvent};

use super::utils::extract_attribute;

const WIDGET_NAMES: &'static [&'static str] = &["block", "p"];

use tui::{
    backend::Backend,
    layout::{Constraint, Direction, Layout},
    widgets::{Block, Borders, Paragraph},
    Frame,
};

fn color_from_str(input: &str) -> Color {
    let input = input.to_lowercase();
    let input = input.as_str();
    match input {
        "reset" => Color::Reset,
        "black" => Color::Black,
        "red" => Color::Red,
        "green" => Color::Green,
        "yellow" => Color::Yellow,
        "blue" => Color::Blue,
        "magenta" => Color::Magenta,
        "cyan" => Color::Cyan,
        "gray" => Color::Gray,
        "darkGray" => Color::DarkGray,
        "lightRed" => Color::LightRed,
        "lightGreen" => Color::LightGreen,
        "lightYellow" => Color::LightYellow,
        "lightBlue" => Color::LightBlue,
        "lightMagenta" => Color::LightMagenta,
        "lightCyan" => Color::LightCyan,
        "white" => Color::White,
        _ => Color::Reset,
    }
}

#[derive(Debug, Clone)]
pub struct MarkupAttribute {
    pub name: String,
    pub value: String,
}

#[derive(Debug)]
pub struct MarkupElement {
    pub deep: usize,
    pub name: String,
    pub text: String,
    pub attributes: HashMap<String, String>,
    pub children: Vec<Rc<RefCell<MarkupElement>>>,
    pub parent_node: Option<Rc<RefCell<MarkupElement>>>,
}

impl Clone for MarkupElement {
    fn clone(&self) -> Self {
        MarkupElement {
            deep: self.deep,
            name: self.name.clone(),
            text: self.text.clone(),
            attributes: self.attributes.clone(),
            children: self.children.clone(),
            parent_node: self.parent_node.clone(),
        }
    }
}

impl fmt::Display for MarkupElement {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let attr_vls: String = self
            .attributes
            .keys()
            .map(|key| {
                let value = self.attributes.get(key);
                let value = if value.is_some() { value.unwrap() } else { "" };
                format!(" {}=\"{}\"", key, value)
            })
            .collect();
        let children: String = self
            .children
            .iter()
            .map(|child| format!("{}", child.as_ref().borrow()))
            .collect();
        let tab = "\t".repeat(self.deep);
        let new_str = format!(
            "{}<{}{}>\n{}\n{}</{}>\n",
            tab, self.name, attr_vls, children, tab, self.name
        );
        fmt::Display::fmt(&new_str, f)
    }
}

#[derive(Debug)]
pub struct MarkupParser {
    pub path: String,
    pub failed: bool,
    pub error: Option<String>,
    pub root: Option<Rc<RefCell<MarkupElement>>>,
}

impl MarkupParser {
    pub fn get_element(node: Option<Rc<RefCell<MarkupElement>>>) -> MarkupElement {
        let r = node.clone().unwrap();
        let r = r.as_ref().borrow().to_owned();
        r
    }

    pub fn is_widget(node_name: &str) -> bool {
        WIDGET_NAMES.contains(&node_name)
    }

    pub fn is_layout(node_name: &str) -> bool {
        node_name.eq("layout")
    }

    pub fn get_border(border: String) -> Borders {
        if border.contains("|") {
            let borders = border
                .split("|")
                .map(|s| String::from(s))
                .map(|s| MarkupParser::get_border(s))
                .collect::<Vec<Borders>>();
            let size = borders.len();
            let mut res = borders[0];
            for i in 1..size {
                res |= borders[i];
            }
            return res;
        }
        let border = match border.to_lowercase().as_str() {
            "all" => Borders::ALL,
            "bottom" => Borders::BOTTOM,
            "top" => Borders::TOP,
            "left" => Borders::LEFT,
            "right" => Borders::RIGHT,
            _ => Borders::NONE,
        };
        border
    }

    pub fn get_constraint(constraint: String) -> Constraint {
        let res = if constraint.ends_with("%") {
            let constraint_value = constraint.replace("%", "");
            let constraint_value = constraint_value.parse::<u16>().unwrap_or(1);
            Constraint::Percentage(constraint_value)
        } else if constraint.ends_with("min") {
            let constraint_value = constraint.replace("min", "");
            let constraint_value = constraint_value.parse::<u16>().unwrap_or(1);
            Constraint::Min(constraint_value)
        } else if constraint.ends_with("max") {
            let constraint_value = constraint.replace("max", "");
            let constraint_value = constraint_value.parse::<u16>().unwrap_or(1);
            Constraint::Max(constraint_value)
        } else if constraint.contains(":") {
            let parts = constraint.split(":");
            let parts: Vec<&str> = parts.collect();
            let x = String::from(parts[0]).parse::<u32>().unwrap_or(1);
            let y = String::from(parts[1]).parse::<u32>().unwrap_or(1);
            Constraint::Ratio(x, y)
        } else {
            let constraint_value = constraint.parse::<u16>().unwrap_or(1);
            Constraint::Length(constraint_value)
        };
        res
    }

    pub fn get_direction(node: &MarkupElement) -> Direction {
        let direction = extract_attribute(node.attributes.clone(), "direction");
        if direction.eq("horizontal") {
            Direction::Horizontal
        } else {
            Direction::Vertical
        }
    }

    pub fn get_alignment(node: &MarkupElement) -> Alignment {
        let align_text = extract_attribute(node.attributes.clone(), "align");
        match align_text.as_str() {
            "center" => Alignment::Center,
            "left" => Alignment::Left,
            "right" => Alignment::Right,
            _ => Alignment::Left,
        }
    }

    pub fn get_styles(node: &MarkupElement) -> Style {
        let mut res = Style::default();
        let styles_text = extract_attribute(node.attributes.clone(), "styles");
        if styles_text.len() < 3 {
            return res;
        }
        let styles_vec = styles_text
            .split(";")
            .map(|style| style.split(":").map(|word| word.trim()).collect())
            .map(|data: Vec<&str>| (data[0], data[1]))
            .collect::<Vec<(&str, &str)>>();
        let styles: HashMap<&str, &str> = styles_vec.into_iter().collect();
        if styles.contains_key("bg") {
            let color = color_from_str(styles.get("bg").unwrap());
            res = res.bg(color);
        }
        if styles.contains_key("fg") {
            let color = color_from_str(styles.get("fg").unwrap());
            res = res.fg(color);
        }
        res
    }

    fn process_block(&self, child: &MarkupElement) -> Block {
        let title = extract_attribute(child.attributes.clone(), "title");
        let border = extract_attribute(child.attributes.clone(), "border");
        let border = MarkupParser::get_border(border);
        let block = Block::default().title(title).borders(border);
        block
    }

    fn process_paragraph(&self, child: &MarkupElement) -> Paragraph {
        let styles = MarkupParser::get_styles(&child.clone());
        let alignment = MarkupParser::get_alignment(&child.clone());
        let block = self.process_block(&child.clone());
        let p = Paragraph::new(child.text.clone())
            .style(styles)
            .alignment(alignment)
            .block(block);
        p
    }

    fn draw_element<B: Backend>(&self, frame: &mut Frame<B>, area: Rect, node: &MarkupElement) {
        let name = node.name.clone();
        let name = name.as_str();
        match name {
            "block" => {
                let widget = self.process_block(&node);
                frame.render_widget(widget, area);
            }
            "p" => {
                let widget = self.process_paragraph(&node);
                frame.render_widget(widget, area);
            }
            _ => {
                let widget = Block::default();
                frame.render_widget(widget, area);
            }
        };
    }

    fn process_layout<B: Backend>(
        &self,
        frame: &mut Frame<B>,
        node: &MarkupElement,
        place: Option<Rect>,
        margin: Option<u16>,
    ) -> Vec<(Rect, MarkupElement)> {
        let direction = MarkupParser::get_direction(node);
        let mut res: Vec<(Rect, MarkupElement)> = vec![];
        let mut constraints: Vec<Constraint> = vec![];
        let mut widgets_info: Vec<(usize, MarkupElement)> = vec![];
        let mut layouts_info: Vec<(usize, MarkupElement)> = vec![];
        for (position, child) in node.children.iter().enumerate() {
            let borrowed_child = child.as_ref().borrow();
            if borrowed_child.name.eq("container") {
                let constraint = extract_attribute(borrowed_child.attributes.clone(), "constraint");
                constraints.push(MarkupParser::get_constraint(constraint));
                let children = borrowed_child.children.clone();
                children
                    .iter()
                    .map(|child| child.as_ref().borrow())
                    .for_each(|child| {
                        let child_name = child.name.as_str();
                        if MarkupParser::is_widget(child_name) {
                            let son = child.clone();
                            if son.children.len() > 0 {
                                let son = son.children[0].clone();
                                let son = son.as_ref();
                                let son = son.borrow();
                                let son_name = son.name.as_str();
                                if son_name.eq("layout") {
                                    layouts_info.push((position, son.clone()));
                                    widgets_info.push((position, child.clone()));
                                } else {
                                    widgets_info.push((position, child.clone()));
                                }
                            } else {
                                widgets_info.push((position, child.clone()));
                            }
                        } else if MarkupParser::is_layout(child_name) {
                            let partial_res = self.process_node(frame, node, None, None);
                            for pair in partial_res.iter() {
                                res.push((pair.0, pair.1.clone()));
                            }
                        }
                    })
            }
        }

        let layout = Layout::default()
            .direction(direction)
            .margin(margin.unwrap_or(0))
            .constraints(constraints.clone().as_ref());

        let chunks = layout.split(place.unwrap_or(frame.size()));

        for (cntr, widget_info) in widgets_info.iter() {
            let counter = *cntr;
            res.push((chunks[counter].clone(), widget_info.clone()));
        }

        for (cntr, layout_info) in layouts_info.iter() {
            let counter = *cntr;
            let place = Some(chunks[counter].clone());
            let parent = layout_info.parent_node.clone().unwrap();
            let parent = parent.as_ref().borrow();
            let border_value = extract_attribute(parent.attributes.clone(), "border");
            let margin = if border_value.eq("none") {
                None
            } else {
                Some(1)
            };
            let partial_res = self.process_node(frame, &layout_info, place, margin);
            for pair in partial_res.iter() {
                res.push((pair.0, pair.1.clone()));
            }
        }
        res
    }

    fn process_node<B: Backend>(
        &self,
        frame: &mut Frame<B>,
        node: &MarkupElement,
        place: Option<Rect>,
        margin: Option<u16>,
    ) -> Vec<(Rect, MarkupElement)> {
        let name = node.name.clone();
        let name = name.as_str();
        let values: Vec<(Rect, MarkupElement)> = match name {
            "layout" => self.process_layout(frame.borrow_mut(), node, place, margin),
            _ => {
                panic!("Invalid node type \"{}\"", name);
            }
        };

        return values;
    }

    pub fn render_ui<B: Backend>(&self, frame: &mut Frame<B>) {
        let root = MarkupParser::get_element(self.root.clone());
        // let prnt = MarkupParser::get_element(self.root.clone());
        // print!("{}", prnt);
        let drawables = self.process_node(frame.borrow_mut(), &root, None, None);
        drawables.iter().for_each(|pair| {
            let area = pair.0;
            let node = pair.1.clone();
            self.draw_element(frame, area, &node);
        });
    }

    pub fn new(path: String) -> MarkupParser {
        if !Path::new(&path).exists() {
            panic!("Markup file does not exist at {}", &path);
        }
        let file = File::open(&path).unwrap();
        let buffer = BufReader::new(file);
        let parser = EventReader::new(buffer);
        let mut root_node: Option<Rc<RefCell<MarkupElement>>> = None;
        let mut current_node: Option<Rc<RefCell<MarkupElement>>> = None;
        let mut parent_node: Option<Rc<RefCell<MarkupElement>>> = None;
        for e in parser {
            match e {
                Ok(XmlEvent::StartElement {
                    name, attributes, ..
                }) => {
                    let mut attrs = HashMap::new();
                    for attr in attributes {
                        attrs.insert(attr.name.local_name, attr.value);
                    }
                    let _id = attrs.get("id").unwrap_or(&String::from("unknown"));
                    let partial = MarkupElement {
                        deep: if parent_node.is_some() {
                            MarkupParser::get_element(parent_node.clone()).deep + 1
                        } else {
                            0
                        },
                        text: String::from("PENDING FROM XML"),
                        name: name.local_name,
                        attributes: attrs,
                        children: vec![],
                        parent_node: parent_node.clone(),
                    };

                    current_node = Some(Rc::new(RefCell::new(partial)));

                    let is_root_defined = root_node.clone().as_ref().is_some();
                    if !is_root_defined {
                        root_node = current_node.clone();
                    }

                    if parent_node.is_some() {
                        let parent = parent_node.clone();
                        let parent = parent.unwrap();
                        let parent = parent.as_ref();
                        let mut parent = parent.borrow_mut();
                        let son = current_node.clone().unwrap();
                        parent.children.push(son);
                    }
                    parent_node = current_node.clone();
                }
                Ok(XmlEvent::Characters(ref r)) => {
                    let node = current_node.clone();
                    let node = node.unwrap();
                    let node = node.as_ref();
                    let mut node = node.borrow_mut();
                    node.text = String::from(r.trim());
                }
                Ok(XmlEvent::EndElement { .. }) => {
                    let p = MarkupParser::get_element(parent_node.clone());
                    parent_node = p.parent_node;
                }
                Ok(XmlEvent::EndDocument { .. }) => {}
                Err(e) => {
                    return MarkupParser {
                        path: path.to_string(),
                        failed: true,
                        error: Some(format!("{}", e.msg())),
                        root: None,
                    };
                }
                _ => {}
            };
        }
        MarkupParser {
            path: path.to_string(),
            failed: false,
            error: None,
            root: root_node.clone(),
        }
    }
}