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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use leptos::html::Data;

use crate::{
    emitter::Emitter,
    parser_helpers::{BlockCell, BlockChildType, Cell, CellType, DataCell, ElementCell, Prop},
};

use super::helpers::*;

pub struct Desugarer {
    pub json: String,
    pub last_id: u32,
}

pub struct ParagraphIndentOptions {
    pub tags_before_non_indents: Vec<&'static str>,
    pub tags_with_non_indent_first_child: Vec<&'static str>,
}

pub enum AttachToEnum {
    BEFORE,
    AFTER,
    BOTH,
}
pub struct IgnoreOptions {
    pub element: &'static str,
    pub attach_to: AttachToEnum,
}

impl Desugarer {
    pub fn new(json: &str, last_id: u32) -> Desugarer {
        Desugarer {
            json: json.to_string(),
            last_id,
        }
    }

    fn count_element(&mut self, root: &DataCell, tag_name: &str, count: &mut usize) {
        match &root.cell_type {
            CellType::Element(el) => {
                if el.name == tag_name {
                    *count += 1;
                } else {
                    el.children
                        .iter()
                        .for_each(|child| self.count_element(child, tag_name, count))
                }
            }
            CellType::Root(el) => el
                .children
                .iter()
                .for_each(|child| self.count_element(child, tag_name, count)),

            _ => (),
        }
    }

    fn find_cell<'a>(
        &self,
        root: &'a DataCell,
        tag_names: &Vec<&str>,
        cells: &mut Vec<&'a DataCell>,
    ) {
        match &root.cell_type {
            CellType::Element(el) => {
                if tag_names.is_empty() || tag_names.contains(&el.name.as_str()) {
                    cells.push(root)
                } else {
                    el.children
                        .iter()
                        .for_each(|child| self.find_cell(child, tag_names, cells))
                }
            }
            CellType::Root(el) => el
                .children
                .iter()
                .for_each(|child| self.find_cell(child, tag_names, cells)),

            _ => (),
        }
    }

    pub fn pre_process_exercises(&mut self) -> Desugarer {
        let mut root: DataCell = serde_json::from_str(&self.json).unwrap();
        let mut exercises: Vec<&DataCell> = Vec::new();
        let binding = root.clone();
        self.find_cell(&binding, &vec!["Exercises"], &mut exercises);

        for exercises_cell in exercises.iter() {
            let mut count: usize = 0;
            self.count_element(exercises_cell, "Exercise", &mut count);
            let mut prop_line = "labels vec![\"0\"".to_string();
            for i in 1..=count - 1 {
                prop_line += &format!(",\"{}\"", i);
            }
            prop_line += "]";

            ElementCell::add_attribute(&mut root, exercises_cell.id, prop_line.as_str());
        }

        Desugarer {
            json: serde_json::to_string_pretty(&root).unwrap(),
            last_id: self.last_id,
        }
    }

    pub fn pre_process_solutions(&mut self) -> Desugarer {
        let mut root: DataCell = serde_json::from_str(&self.json).unwrap();
        let mut solutions: Vec<&DataCell> = Vec::new();
        let binding = root.clone();
        self.find_cell(&binding, &vec!["Solution"], &mut solutions);

        for (i, solution_cell) in solutions.iter().enumerate() {
            let prop_line = format!("solution_number {}", i);

            ElementCell::add_attribute(&mut root, solution_cell.id, prop_line.as_str());
        }

        Desugarer {
            json: serde_json::to_string_pretty(&root).unwrap(),
            last_id: self.last_id,
        }
    }

    pub fn wrap_children(
        &mut self,
        elements: Vec<&str>,
        wrap_with: &str,
        ignore_elements: &Option<Vec<IgnoreOptions>>,
    ) -> Desugarer {
        // elements are what we want to wrap it's children with wrap_with

        let mut root: DataCell = serde_json::from_str(&self.json).unwrap();
        let mut _elements: Vec<&DataCell> = Vec::new();
        let binding = root.clone();
        self.find_cell(&binding, &elements, &mut _elements);

        for (i, element) in _elements.iter().enumerate() {
            //let prop_line = format!("solution_number {}", i);
            if let CellType::Element(el) = &element.cell_type {
                let mut include_prev_child = false;
                let mut include_in_prev_wrapper = false;
                let mut add_wrapper = true;

                el.children.iter().enumerate().for_each(|(idx, child)| {
                    let mut element_ignored = None;
                    if let Some(ignore_options) = ignore_elements {
                        ignore_options.iter().any(|option| {
                            if let CellType::Element(child_el) = &child.cell_type {
                                if option.element == child_el.name {
                                    element_ignored = Some(option);
                                    add_wrapper = false;
                                    return true;
                                }
                            }
                            add_wrapper = true;
                            false
                        });
                    }

                    if let Some(el_ignored) = element_ignored {
                        match el_ignored.attach_to {
                            AttachToEnum::BEFORE => {
                                // move to previous added wrapper if there is one
                                if idx == 0 {
                                    add_wrapper = true;
                                } else {
                                    ElementCell::move_cell(
                                        &mut root,
                                        (element.id, child.id),
                                        self.last_id,
                                    );
                                }
                            }
                            AttachToEnum::AFTER => {
                                // move to next wrapper
                                include_prev_child = true
                            }
                            _ => {
                                // this and next block should be in previous added wrapper
                                if idx == 0 {
                                    self.last_id += 1;
                                    ElementCell::add_cell(
                                        &mut root,
                                        element.id,
                                        self.last_id,
                                        wrap_with,
                                    );
                                }
                                ElementCell::move_cell(
                                    &mut root,
                                    (element.id, child.id),
                                    self.last_id,
                                );
                                include_in_prev_wrapper = true
                            }
                        }
                    } else if include_in_prev_wrapper {
                        ElementCell::move_cell(&mut root, (element.id, child.id), self.last_id);
                        include_in_prev_wrapper = false;

                        add_wrapper = false
                    }

                    if add_wrapper {
                        self.last_id += 1;
                        ElementCell::add_cell(&mut root, element.id, self.last_id, wrap_with);

                        if include_prev_child {
                            ElementCell::move_cell(
                                &mut root,
                                (element.id, el.children[idx - 1].id),
                                self.last_id,
                            );
                            include_prev_child = false
                        }
                        ElementCell::move_cell(&mut root, (element.id, child.id), self.last_id);
                    }
                });
            }
        }

        Desugarer {
            json: serde_json::to_string_pretty(&root).unwrap(),
            last_id: self.last_id,
        }
    }

    pub fn add_indent(&mut self, options: &ParagraphIndentOptions) -> Desugarer {
        // A paragraph has an indent by default except:

        let mut root: DataCell = serde_json::from_str(&self.json).unwrap();
        let mut _elements: Vec<&DataCell> = Vec::new();
        let binding = root.clone();

        self.find_cell(&binding, &vec!["Paragraph"], &mut _elements);

        for (element) in _elements.iter() {
            let parent: Option<&mut DataCell> =
                DataCell::get_cell_by_id(&mut root, element.parent_id);

            // only paragraph elements that have block cell
            if Self::paragraph_of_blocks(element) {
                continue;
            }
            // the first paragraph of every section, exercise, or example does not have an indent
            if Self::is_first_child(element.id, &parent, options) {
                continue;
            }
            // $$, __,  |_ paragraphs
            if Self::is_delimited(element) {
                continue;
            }
            // a paragraph that follows a paragraph ending with the $$, __,  |_ delimeters does not have an indent
            if Self::prev_is_delimited(element.id, &parent) {
                continue;
            }
            // a paragraph that follows tags defined in
            if Self::tags_before_non_indents(element.id, &parent, &options) {
                continue;
            }
            self.last_id += 1;
            ElementCell::add_cell(&mut root, element.id, self.last_id, "Indent");
            ElementCell::move_children(&mut root, element.id, self.last_id);
        }

        Desugarer {
            json: serde_json::to_string_pretty(&root).unwrap(),
            last_id: self.last_id,
        }
    }

    pub fn paragraph_of_blocks(element: &DataCell) -> bool {
        if let CellType::Element(el) = &element.cell_type {
            if el.children.first().is_some_and(|c| {
                if let CellType::Block(_) = &c.cell_type {
                    false
                } else {
                    true
                }
            }) {
                return true;
            }
        }
        false
    }

    pub fn is_first_child(
        element_id: u32,
        parent: &Option<&mut DataCell>,
        options: &ParagraphIndentOptions,
    ) -> bool {
        if let Some(parent) = parent {
            if let CellType::Element(parent) = &parent.cell_type {
                if options
                    .tags_with_non_indent_first_child
                    .contains(&parent.name.as_str())
                    && parent.children.first().is_some_and(|c| c.id == element_id)
                {
                    return true;
                }
            }
        }
        false
    }

    pub fn is_delimited(element: &DataCell) -> bool {
        if let CellType::Element(element) = &element.cell_type {
            if let Some(block) = element.children.first() {
                if let CellType::Block(block) = &block.cell_type {
                    if let Some(block) = block.children.first() {
                        if let BlockChildType::Delimited(b) = &block {
                            return b.delimeter == "$$"
                                || b.delimeter == "__"
                                || b.delimeter == "_|";
                        }
                    }
                }
            }
        }
        false
    }

    pub fn prev_is_delimited(element_id: u32, parent: &Option<&mut DataCell>) -> bool {
        if let Some(parent) = parent {
            if let CellType::Element(parent) = &parent.cell_type {
                let mut prev_el: Option<&DataCell> = None;
                for child in &parent.children {
                    if child.id == element_id {
                        break;
                    }
                    prev_el = Some(&child)
                }
                if prev_el.is_some_and(|p| Self::is_delimited(p)) {
                    return true;
                }
            }
        }
        false
    }

    pub fn tags_before_non_indents(
        element_id: u32,
        parent: &Option<&mut DataCell>,
        option: &ParagraphIndentOptions,
    ) -> bool {
        if let Some(parent) = parent {
            if let CellType::Element(parent) = &parent.cell_type {
                let mut prev_el: Option<&DataCell> = None;
                for child in &parent.children {
                    if child.id == element_id {
                        break;
                    }
                    prev_el = Some(&child)
                }
                if let Some(prev_el) = prev_el {
                    if let CellType::Element(prev_el) = &prev_el.cell_type {
                        if prev_el.children.first().is_some_and(|p| {
                            if let CellType::Element(el) = &p.cell_type {
                                return option.tags_before_non_indents.contains(&el.name.as_str());
                            } else {
                                false
                            }
                        }) {
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    /*    pub fn pre_process_exercises(&mut self) -> Desugarer {
           let mut lines: Vec<String> = self.json.lines().map(|s| s.to_string()).collect();
           let binding = lines.clone();

           /* Wrap exercises inside Exercises component */
           /* Right now this works only if there are consuctive exercises */
           let mut exercises = binding
               .iter()
               .enumerate()
               .filter(|(_, line)| line.trim() == "|> Exercise");

           if let Some(exo) = exercises.nth(0) {
               // add prop line which is like labels=vec!["0", "1", "2", "3"]
               let mut props_string = "    labels=vec![\"0\"".to_string();
               for i in 1..exercises.clone().count() + 1 {
                   props_string += &format!(",\"{}\"", i);
               }
               props_string += "]";

               lines.insert(exo.0 - 1, props_string);
           }

           Desugarer {
               json: lines.join("\n"),
           }
       }

       pub fn pre_process_solutions(&mut self) -> Desugarer {
           let mut lines: Vec<String> = self.json.lines().map(|s| s.to_string()).collect();
           let binding = lines.clone();

           let mut solutions = binding
               .iter()
               .enumerate()
               .filter(|(_, line)| line.trim() == "|> Solution");

           for i in 0..solutions.clone().count() {
               let solution = solutions.next().unwrap();
               let solution_tag_line = solution.0 + i;

               let indent = solution.1.len() - solution.1.trim_start().len();
               let mut indent_string = "    ".to_string();
               for _ in 0..indent {
                   indent_string += " ";
               }
               let props_string = format!("{}solution_number={}", indent_string, i);
               lines.insert(solution_tag_line + 1, props_string);
           }
           Desugarer {
               json: lines.join("\n"),
           }
       }

       pub fn remove_empty_line_above(
           &mut self,
           tags: Vec<&str>,
           ignore_prop: Option<(&str, &str)>, // (key, value)
           parser: &mut Emitter,
       ) -> Desugarer {
           // Removes empty lines above tags

           let mut lines: Vec<String> = self.json.lines().map(|s| s.to_string()).collect();
           let binding = lines.clone();
           let mut lines_removed = 0;

           binding
               .iter()
               .enumerate()
               .filter(|(i, line)| {
                   let tag_found = line.trim().starts_with("|> ") && tags.contains(&&line.trim()[3..]);
                   let mut should_ignore = false;

                   if tag_found && ignore_prop.is_some() {
                       // search props
                       let indent = get_line_indent(line);
                       let mut j = *i + 1;
                       let next_line = binding.iter().nth(j);
                       if let Some(mut next_line) = next_line {
                           let mut next_line_indent = get_line_indent(next_line);

                           while next_line_indent > indent && !should_ignore {
                               let prop_key = next_line.trim().split_once(" ");
                               if let Some(prop_key) = prop_key {
                                   should_ignore = prop_key.0 == ignore_prop.unwrap().0
                                       && prop_key.1 == ignore_prop.unwrap().1
                               }
                               j += 1;
                               if binding.iter().nth(j).is_none() {
                                   break;
                               }
                               next_line = binding.iter().nth(j).unwrap();
                               next_line_indent = get_line_indent(next_line);
                           }
                       }
                   }
                   tag_found && !should_ignore
               })
               .for_each(|tag| {
                   lines.remove(tag.0 - 1 - lines_removed);
                   lines_removed += 1;
                   parser.track_line_delta -= 1
               });

           Desugarer {
               json: lines.join("\n"),
           }
       }

       pub fn auto_increamental_title(
           &mut self,

           tag_name: &str,
           title_label: &str,
           wrapper: Option<&str>,
           wrapper_break_on: Option<&str>,
       ) -> Desugarer {
           let mut lines: Vec<String> = self.json.lines().map(|s| s.to_string()).collect();
           let binding = lines.clone();
           let mut jump = 2;

           let _ = binding
               .iter()
               .enumerate()
               .filter(|(_, line)| line.trim() == format!("|> {}", tag_name))
               .enumerate()
               .for_each(|(idx, ex)| {
                   // Suppose there are not props for Example , we add title at 3rd line
                   let indent = ex.1.len() - ex.1.trim_start().len();
                   let mut indent_string = "    ".to_string();
                   for _ in 0..indent {
                       indent_string += " ";
                   }
                   if let Some(wrapper) = wrapper {
                       lines.insert(
                           ex.0 + jump + idx,
                           format!("{}|> {}", indent_string, wrapper),
                       );
                       lines.insert(ex.0 + jump + 1 + idx, "".to_string());
                       indent_string += "    ";
                       jump += 2;

                       let mut i = ex.0 + jump + idx;

                       while i < lines.len()
                           && lines[i].trim() != format!("|> {}", wrapper_break_on.unwrap())
                           && (lines[i].is_empty()
                               || lines[i].chars().all(char::is_whitespace)
                               || lines[i].len() - lines[i].trim_start().len() > indent)
                       {
                           i += 1;
                       }

                       for i in ex.0 + jump + idx..i {
                           if lines[i].is_empty() || lines[i].chars().all(char::is_whitespace) {
                               continue;
                           };
                           lines[i] = format!("    {}", lines[i]);
                       }
                   }
                   lines.insert(
                       ex.0 + jump + idx,
                       format!("{}*{} {}.*", indent_string, title_label, idx + 1),
                   );
               });

           Desugarer {
               json: lines.join("\n"),
           }
       }
    */
}