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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
use crate::constants::{COLON, NEWLINE, RBRACK, SPACE, STAR};
use crate::node_pool::NodeID;
use crate::parse::{parse_element, parse_object};
use crate::types::{Cursor, Expr, MatchError, ParseOpts, Parseable, Parser, Result};
use crate::utils::{bytes_to_str, Match};

use super::{parse_property, PropertyDrawer};

const ORG_TODO_KEYWORDS: [&str; 2] = ["TODO", "DONE"];

// STARS KEYWORD PRIORITY TITLE TAGS
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Heading<'a> {
    pub heading_level: HeadingLevel,
    // Org-Todo type stuff
    pub keyword: Option<&'a str>,
    pub priority: Option<Priority>,
    pub title: Option<(&'a str, Vec<NodeID>)>,
    pub tags: Option<Vec<Tag<'a>>>,
    pub properties: Option<PropertyDrawer<'a>>,
    pub children: Option<Vec<NodeID>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Priority {
    A,
    B,
    C,
    Num(u8),
}

/// Headline Tag
///
/// ```example
/// * head :tag:
/// ** child :child:
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Tag<'a> {
    /// Tag unique to the individual headline.
    Raw(&'a str),
    /// NodeID referring to the parent headline.
    Loc(NodeID),
}

/// Enum of possible headline levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum HeadingLevel {
    One,
    Two,
    Three,
    Four,
    Five,
    Six,
}

// Implemented not via `TryFrom` so that `MatchError` can be private
// while keeping the struct Public
fn try_heading_levelfrom(value: usize) -> Result<HeadingLevel> {
    match value {
        1 => Ok(HeadingLevel::One),
        2 => Ok(HeadingLevel::Two),
        3 => Ok(HeadingLevel::Three),
        4 => Ok(HeadingLevel::Four),
        5 => Ok(HeadingLevel::Five),
        6 => Ok(HeadingLevel::Six),
        _ => Err(MatchError::InvalidLogic),
    }
}

impl From<HeadingLevel> for u8 {
    fn from(value: HeadingLevel) -> Self {
        match value {
            HeadingLevel::One => 1,
            HeadingLevel::Two => 2,
            HeadingLevel::Three => 3,
            HeadingLevel::Four => 4,
            HeadingLevel::Five => 5,
            HeadingLevel::Six => 6,
        }
    }
}

impl<'a> Parseable<'a> for Heading<'a> {
    fn parse(
        parser: &mut Parser<'a>,
        mut cursor: Cursor<'a>,
        parent: Option<NodeID>,
        parse_opts: ParseOpts,
    ) -> Result<NodeID> {
        let start = cursor.index;

        let stars = Heading::parse_stars(cursor)?;
        let heading_level = stars.obj;
        cursor.move_to(stars.end);

        // guaranteed to allocate since this is a valid headline. Setup the id
        let reserved_id = parser.pool.reserve_id();

        let keyword: Option<&str> = if let Ok(keyword_match) = Heading::parse_keyword(cursor) {
            cursor.move_to(keyword_match.end);
            Some(keyword_match.obj)
        } else {
            None
        };

        let priority: Option<Priority> = if let Ok(prio_match) = Heading::parse_priority(cursor) {
            cursor.move_to(prio_match.end);
            Some(prio_match.obj)
        } else {
            None
        };

        let tag_match = Heading::parse_tag(cursor);
        // if the tags are valid:
        // tag_match.start: space
        // tag_match.end: past newline
        //
        // otherwise:
        //
        // tag_match.start: newline
        // tag_match.end: past newline
        let tags = tag_match.obj;

        // use separate idx and shorten the bottom and top of the byte_arr
        // to trim

        // try to trim whitespace off the beginning and end of the area
        // we're searching
        let mut title_end = tag_match.start;
        while cursor[title_end] == SPACE && title_end > cursor.index {
            title_end -= 1;
        }
        let mut temp_cursor = cursor.cut_off(title_end + 1);

        let mut target = None;
        // FIXME: currently repeating work trimming hte beginning at skip_ws and with trim_start
        let title = if bytes_to_str(temp_cursor.rest()).trim_start().is_empty() {
            None
        } else {
            let mut title_vec: Vec<NodeID> = Vec::new();

            temp_cursor.skip_ws();
            let title_start = temp_cursor.index;
            while let Ok(title_id) =
                parse_object(parser, temp_cursor, Some(reserved_id), parse_opts)
            {
                title_vec.push(title_id);
                temp_cursor.move_to(parser.pool[title_id].end);
            }

            let title_entry = cursor.clamp(title_start, title_end + 1);
            target = Some(parser.generate_target(title_entry));

            Some((title_entry, title_vec))
        };

        // jump past the newline
        cursor.move_to(tag_match.end);

        // Handle subelements

        let properties = if let Ok(ret) = parse_property(cursor) {
            cursor.index = ret.end;
            Some(ret.obj)
        } else {
            None
        };

        let mut section_vec: Vec<NodeID> = Vec::new();

        while let Ok(element_id) = parse_element(parser, cursor, Some(reserved_id), parse_opts) {
            if let Expr::Heading(ref mut heading) = parser.pool[element_id].obj {
                if u8::from(heading_level) < u8::from(heading.heading_level) {
                    if let Some(tag_vec) = &mut heading.tags {
                        tag_vec.push(Tag::Loc(reserved_id));
                    } else {
                        heading.tags = Some(vec![Tag::Loc(reserved_id)]);
                    }
                } else {
                    break;
                }
            }

            section_vec.push(element_id);
            cursor.move_to(parser.pool[element_id].end);
        }

        let children = if section_vec.is_empty() {
            None
        } else {
            Some(section_vec)
        };

        let ret_id = parser.alloc_with_id(
            Self {
                heading_level,
                keyword,
                priority,
                title,
                tags,
                children,
                properties,
            },
            start,
            cursor.index,
            parent,
            reserved_id,
        );
        parser.pool[ret_id].id_target = target;
        Ok(ret_id)
    }
}

impl<'a> Heading<'a> {
    fn parse_stars(cursor: Cursor) -> Result<Match<HeadingLevel>> {
        let ret = cursor.fn_while(|chr: u8| chr == STAR)?;

        if cursor[ret.end] != SPACE {
            Err(MatchError::InvalidLogic)
        } else {
            let heading_level: HeadingLevel = try_heading_levelfrom(ret.end - cursor.index)?;
            Ok(Match {
                start: cursor.index,
                end: ret.end,
                obj: heading_level,
            })
            // Ok(ret.end);
        }
    }

    fn parse_keyword(mut cursor: Cursor) -> Result<Match<&str>> {
        let start = cursor.index;
        cursor.skip_ws();

        for (i, val) in ORG_TODO_KEYWORDS.iter().enumerate() {
            // TODO: read up to a whitespace and determine if it's in phf set for keywords
            // this is currently O(n), we can make it O(1)
            if cursor.word(val).is_ok() {
                // keep going in if not whitespace
                // because a keyword might be a subset of another,,,
                if cursor.try_curr()?.is_ascii_whitespace() {
                    return Ok(Match {
                        start,
                        end: cursor.index, // don't move 1 ahead, in case it's a newline
                        obj: val,
                    });
                } else {
                    cursor.index -= val.len();
                }
            }
        }

        Err(MatchError::InvalidLogic)
    }

    // Recognizes the following patterns:
    // [#A]
    // [#1]
    // [#12]
    // TODO: we don't respect the 65 thing for numbers
    fn parse_priority(mut cursor: Cursor) -> Result<Match<Priority>> {
        let start = cursor.index;
        cursor.skip_ws();
        // TODO: check if this is true
        // FIXME breaks in * [#A]EOF

        let end_idx;
        let ret_prio: Priority;
        cursor.word("[#")?;

        // #[A] OR #[1]
        if cursor.try_curr()?.is_ascii_alphanumeric() && cursor.peek(1)? == RBRACK {
            end_idx = cursor.index + 2;
            ret_prio = match cursor.curr() {
                b'A' => Priority::A,
                b'B' => Priority::B,
                b'C' => Priority::C,
                num => Priority::Num(num - 48),
            };
        }
        // #[64]
        else if cursor.curr().is_ascii_digit()
            && cursor.peek(1)?.is_ascii_digit()
            && cursor.peek(2)? == RBRACK
        {
            end_idx = cursor.index + 3;
            // convert digits from their ascii rep, then add.
            // NOTE: all two digit numbers are valid u8, cannot overflow
            ret_prio = Priority::Num(10 * (cursor.curr() - 48) + (cursor.peek(1)? - 48));
        } else {
            return Err(MatchError::InvalidLogic);
        }

        Ok(Match {
            start,
            end: end_idx,
            obj: ret_prio,
        })
    }

    fn parse_tag(mut cursor: Cursor) -> Match<Option<Vec<Tag>>> {
        // we parse tags backwards
        let start = cursor.index;
        cursor.adv_till_byte(NEWLINE);
        let nl_loc = cursor.index;
        cursor.prev();

        while cursor.curr() == SPACE {
            cursor.prev();
        }

        if cursor.curr() == COLON {
            let mut clamp_ind = cursor.index;
            cursor.prev();
            let mut tag_vec: Vec<Tag> = Vec::new();

            while cursor.index >= start {
                if cursor.curr().is_ascii_alphanumeric()
                    | matches!(cursor.curr(), b'_' | b'@' | b'#' | b'%')
                {
                    cursor.prev();
                } else if cursor.curr() == COLON && clamp_ind.abs_diff(cursor.index) > 1 {
                    let new_str = cursor.clamp(cursor.index + 1, clamp_ind);
                    tag_vec.push(Tag::Raw(new_str));
                    clamp_ind = cursor.index;
                    if cursor[cursor.index - 1] == SPACE {
                        // end the search
                        return Match {
                            start: cursor.index - 1,
                            end: nl_loc + 1,
                            obj: Some(tag_vec),
                        };
                    } else {
                        // otherwise, keep going
                        cursor.prev();
                    }
                } else {
                    // invalid input: reset temp_ind back to end
                    return Match {
                        start: nl_loc,
                        end: nl_loc + 1,
                        obj: None,
                    };
                }
            }
        }

        Match {
            start: nl_loc,
            end: nl_loc + 1,
            obj: None,
        }
        // we reached the start element, without hitting a space. no tags
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use crate::element::PropertyDrawer;
    use crate::parse_org;
    use crate::types::Expr;

    use super::Heading;

    fn get_head<'a>(input: &'a str) -> Heading<'a> {
        parse_org(input)
            .pool
            .iter()
            .find_map(|x| {
                if let Expr::Heading(heading) = &x.obj {
                    Some(heading)
                } else {
                    None
                }
            })
            .cloned()
            .unwrap()
    }
    #[test]
    fn basic_headline() {
        let input = "* \n";

        let head = get_head(input);
        assert_eq!(
            head,
            Heading {
                heading_level: crate::element::HeadingLevel::One,
                keyword: None,
                priority: None,
                title: None,
                tags: None,
                properties: None,
                children: None,
            }
        )
    }

    #[test]
    fn headline_stars() {
        let input = "****  \n";

        let head = get_head(input);
        assert_eq!(
            head,
            Heading {
                heading_level: crate::element::HeadingLevel::Four,
                keyword: None,
                priority: None,
                title: None,
                tags: None,
                properties: None,
                children: None,
            }
        )
    }

    #[test]
    #[should_panic]
    fn headline_too_many_stars() {
        // panics because we'd unwrap on the case of no headings
        let input = "*********  \n";

        let head = get_head(input);
    }

    #[test]
    fn headline_title() {
        let inp = "*         title                                                \n";

        dbg!(parse_org(inp));
    }

    #[test]
    fn headline_keyword() {
        let input = "* TODO \n";

        let head = get_head(input);
        assert_eq!(
            head,
            Heading {
                heading_level: crate::element::HeadingLevel::One,
                keyword: Some("TODO"),
                priority: None,
                title: None,
                tags: None,
                properties: None,
                children: None,
            }
        )
    }

    #[test]
    fn headline_prio() {
        let input = "* [#A] \n";

        let head = get_head(input);
        assert_eq!(
            head,
            Heading {
                heading_level: crate::element::HeadingLevel::One,
                keyword: None,
                priority: Some(crate::element::Priority::A),
                title: None,
                tags: None,
                properties: None,
                children: None,
            }
        )
    }

    #[test]
    fn headline_tag() {
        let inp = "* meow :tagone:\n";

        dbg!(parse_org(inp));
    }

    #[test]
    fn headline_tags() {
        let inp = "* meow :tagone:tagtwo:\n";

        dbg!(parse_org(inp));
    }

    #[test]
    fn headline_tags_bad() {
        let inp = "* meow one:tagone:tagtwo:\n";

        dbg!(parse_org(inp));
    }

    #[test]
    fn headline_tags_bad2() {
        let inp = "* meow :tagone::\n";

        dbg!(parse_org(inp));
    }

    #[test]
    fn headline_prio_keyword() {
        let input = "* TODO [#A] \n";

        let head = get_head(input);
        assert_eq!(
            head,
            Heading {
                heading_level: crate::element::HeadingLevel::One,
                keyword: Some("TODO"),
                priority: Some(crate::element::Priority::A),
                title: None,
                tags: None,
                properties: None,
                children: None,
            }
        )
    }

    #[test]
    fn headline_prio_keyword_title() {
        let inp = "* TODO [#A] SWAG \n";

        dbg!(parse_org(inp));
    }

    #[test]
    fn headline_prio_keyword_decorated_title() {
        let inp = "* TODO [#A] *one* two /three/ /four* \n";

        dbg!(parse_org(inp));
    }

    #[test]
    fn headline_everything() {
        let inp = r"* DONE [#0] *one* two /three/ /four*       :one:two:three:four:
more content here this is a pargraph
** [#1] descendant headline :five:
*** [#2] inherit the tags
** [#3] different level
subcontent
this

is a different paragraph
id) =
more subcontent

* [#4] separate andy
";

        let pool = parse_org(inp);
        pool.print_tree();
    }

    #[test]
    fn properties_check() {
        let input = r"
* a
:properties:
:name: val
:end:

";

        let head = get_head(input);
        let got_prop = head.properties.as_ref().unwrap();
        assert_eq!(
            got_prop,
            &PropertyDrawer::from([("name", Cow::from("val"))])
        );

        let input = r"
* a
:properties:
:name: val
:name+: val again
:end:

";
        let head = get_head(input);
        let got_prop = head.properties.as_ref().unwrap();
        assert_eq!(
            got_prop,
            &PropertyDrawer::from([("name", Cow::from("val val again"))])
        );
    }

    #[test]
    fn tag_parse() {
        let input = r"
* q ac:qbc:
qqqqq

aaaa";

        let pool = parse_org(input);
        pool.print_tree();
    }
}