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
601
602
603
//! Todo is NOT timezone-aware

use chrono::NaiveDate;
use itertools::Itertools;
use section::Section;
use std::{error, fmt, fs::read_to_string, fs::OpenOptions, io::Write, path::PathBuf, str};

mod day;
mod section;
mod task;
mod util;

pub use util::today;
use util::*;

pub use day::{Day, DayIterator};
use task::Task;

#[derive(PartialEq, Debug, Clone)]
pub struct Todo {
    pub days: Vec<Day>,
    pub file_path: PathBuf,
}

impl Todo {
    pub fn new(path: Option<&str>) -> Result<Todo> {
        let path: PathBuf = match path {
            // if path present but file doesnt exist, create it
            Some(path) => {
                if let Err(_error) = OpenOptions::new().read(true).open(path) {
                    OpenOptions::new().write(true).create(true).open(path)?;
                };
                path.into()
            }
            // if path not present, create default file if possible
            None => {
                if let Err(_error) = OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(DEFAULT_TODO_FILE)
                {
                    return err!("File with default name {DEFAULT_TODO_FILE} already exists");
                }
                DEFAULT_TODO_FILE.into()
            }
        };

        // load from file or create new blank one
        let todo = Todo::load(&path).unwrap_or(Todo {
            days: Vec::<Day>::new(),
            file_path: path,
        });

        Ok(todo)
    }

    fn last_day(&self) -> Option<&Day> {
        if self.days.len() == 0 {
            return None;
        }

        let mut last_day = &self.days[0];
        for day in &self.days {
            if day.date > last_day.date {
                last_day = &day;
            }
        }
        Some(last_day)
    }

    fn last_day_pos(&self) -> Option<usize> {
        let last_day = self.last_day()?;
        Some(
            self.days
                .iter()
                .position(|day| day.date == last_day.date)
                // create section if it doesnt exist
                .expect("Unable to find last_day pos"),
        )
    }

    /// Creates new day with all tasks/sections from most recent day and cleared Done section
    /// next_day is idempotent, meaning it will do nothing if today already exists in days
    pub fn next_day(&mut self) {
        let mut new_day = match self.last_day() {
            Some(last_day) => {
                // days and today is created: do nothing
                if last_day.date == today() {
                    return;
                }
                // days but no today: copy last day
                let mut clone_last_day = last_day.clone();
                clone_last_day.date = today();
                clone_last_day
            }
            // no days: create new empty day
            None => Day::new(today()),
        };

        // clear "Done" section, create one if didnt find
        match new_day
            .sections
            .iter()
            .position(|section| section.name == "Done")
        {
            Some(pos) => {
                new_day.sections[pos].tasks = Vec::<Task>::new();
            }
            None => {
                let sec = Section::new("Done");
                new_day.sections.push(sec);
            }
        }

        self.days.push(new_day);
    }

    pub fn save(&mut self) -> Result<()> {
        if let Some(last_day_in_file) = get_last_day(&self.file_path) {
            if last_day_in_file > today() {
                return err!("Invalid date: date on file is ahead of today");
            }
        }

        // don't save if file is up to date
        let file_todo = Todo::load(&self.file_path)?;
        if file_todo == *self {
            return err!("File already up to date");
        }

        let mut f = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&self.file_path)?;
        f.write_all(format!("{self}\n").as_bytes())?;
        Ok(())
    }

    pub fn load(todo_file: &PathBuf) -> Result<Todo> {
        if let Some(last_day) = get_last_day(todo_file) {
            if last_day > today() {
                return err!("Invalid date: date on file is ahead of today");
            }
        }
        let mut todo: Todo = read_to_string(&todo_file)
            .expect("Unable to read file")
            .parse()
            .expect("Unable to parse file contents");
        todo.file_path = todo_file.to_path_buf();
        Ok(todo)
    }

    pub fn add(&mut self, task_txt: &str, section: &str) -> Result<()> {
        // make sure current day exists
        self.next_day();

        let task: Task = task_txt.parse()?;
        let day_pos = self.last_day_pos().expect("Could not get last day pos");

        // find section position in vec
        let sections = &mut self.days[day_pos].sections;

        let section_pos = sections
            .iter()
            .position(|sec| sec.name == section)
            // create section if it doesnt exist
            .unwrap_or_else(|| {
                sections.push(Section::new(section));
                sections.len() - 1
            });

        // put task in section
        self.days[day_pos].sections[section_pos].tasks.push(task);
        Ok(())
    }
}

impl str::FromStr for Todo {
    type Err = Box<dyn error::Error + Send + Sync>;
    fn from_str(s: &str) -> Result<Self> {
        let text = s.trim().to_string();
        let mut days: Vec<Day> = Vec::new();
        let day_iter = DayIterator::new(&text);

        let old_date = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
        let mut last_day = Day::new(old_date); // set date to old date

        for day in day_iter {
            if day.date > last_day.date {
                last_day = day.clone();
            }
            days.push(day);
        }

        Ok(Todo {
            days,
            file_path: PathBuf::new(), // no path to give, is this an issue?
        })
    }
}

impl fmt::Display for Todo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let days = self.days.iter().join("\n");
        write!(f, "{days}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::section::Section;
    use crate::task::Task;

    use chrono::Duration as ChronoDuration;
    use chrono::NaiveDate;
    use indoc::indoc;
    use std::io::Write;
    use tempfile::NamedTempFile;

    /// Creates a tmp file with string contents and return the file path
    fn create_file_with_contents(contents: String) -> NamedTempFile {
        let mut file = NamedTempFile::new().expect("Unable to create tmp file");
        file.write_all(contents.as_bytes())
            .expect("Unable to write to tmp file");
        file
    }

    #[test]
    fn parse_todo() {
        let file = create_file_with_contents(
            indoc! {"
            [2024-03-06]
            Section 1
            - task 1
            - task 3
            - task 2
            Done

            [2024-03-07]
            Section 2
            - task 11
            - task 31
            - task 21
            Done
            - task 4
        "}
            .to_string(),
        );
        let path = file.path().to_path_buf();
        let expected = Todo {
            days: vec![
                Day {
                    date: NaiveDate::from_ymd_opt(2024, 3, 6).unwrap(),
                    sections: vec![
                        Section {
                            name: "Section 1".to_string(),
                            tasks: vec![
                                Task {
                                    text: "task 1".to_string(),
                                },
                                Task {
                                    text: "task 3".to_string(),
                                },
                                Task {
                                    text: "task 2".to_string(),
                                },
                            ],
                        },
                        Section {
                            name: "Done".to_string(),
                            tasks: vec![],
                        },
                    ],
                },
                Day {
                    date: NaiveDate::from_ymd_opt(2024, 3, 7).unwrap(),
                    sections: vec![
                        Section {
                            name: "Section 2".to_string(),
                            tasks: vec![
                                Task {
                                    text: "task 11".to_string(),
                                },
                                Task {
                                    text: "task 31".to_string(),
                                },
                                Task {
                                    text: "task 21".to_string(),
                                },
                            ],
                        },
                        Section {
                            name: "Done".to_string(),
                            tasks: vec![Task {
                                text: "task 4".to_string(),
                            }],
                        },
                    ],
                },
            ],
            file_path: path.clone(),
        };

        let actual = Todo::load(&path).expect("Unable to load file");
        assert_eq!(actual, expected);
    }

    #[test]
    fn save_todo() {
        let expected = indoc! {"
            [2024-03-06]
            Section 1
            - task 1
            - task 3
            - task 2

            Done

            [2024-03-07]
            Section 2
            - task 11
            - task 31
            - task 21

            Done

        "};

        let file = NamedTempFile::new().expect("Unable to create tmp file");
        let path = file.path();
        let mut todo = Todo {
            file_path: path.to_path_buf(),
            days: vec![
                Day {
                    date: NaiveDate::from_ymd_opt(2024, 3, 6).unwrap(),
                    sections: vec![
                        Section {
                            name: "Section 1".to_string(),
                            tasks: vec![
                                Task {
                                    text: "task 1".to_string(),
                                },
                                Task {
                                    text: "task 3".to_string(),
                                },
                                Task {
                                    text: "task 2".to_string(),
                                },
                            ],
                        },
                        Section {
                            name: "Done".to_string(),
                            tasks: vec![],
                        },
                    ],
                },
                Day {
                    date: NaiveDate::from_ymd_opt(2024, 3, 7).unwrap(),
                    sections: vec![
                        Section {
                            name: "Section 2".to_string(),
                            tasks: vec![
                                Task {
                                    text: "task 11".to_string(),
                                },
                                Task {
                                    text: "task 31".to_string(),
                                },
                                Task {
                                    text: "task 21".to_string(),
                                },
                            ],
                        },
                        Section {
                            name: "Done".to_string(),
                            tasks: vec![],
                        },
                    ],
                },
            ],
        };

        let _ = todo.save().expect("Unable to load file");

        let actual = read_to_string(&path).expect("Unable to read file");
        assert_eq!(actual, expected);
    }

    #[test]
    fn add_task() {
        let base = Todo {
            days: vec![Day {
                date: today(),
                sections: vec![
                    Section {
                        name: "Section 1".to_string(),
                        tasks: vec![
                            Task {
                                text: "task 1".to_string(),
                            },
                            Task {
                                text: "task 2".to_string(),
                            },
                            Task {
                                text: "task 3".to_string(),
                            },
                        ],
                    },
                    Section {
                        name: "Done".to_string(),
                        tasks: vec![],
                    },
                ],
            }],
            file_path: PathBuf::new(),
        };

        let expected = Todo {
            days: vec![Day {
                date: today(),
                sections: vec![
                    Section {
                        name: "Section 1".to_string(),
                        tasks: vec![
                            Task {
                                text: "task 1".to_string(),
                            },
                            Task {
                                text: "task 2".to_string(),
                            },
                            Task {
                                text: "task 3".to_string(),
                            },
                            Task {
                                text: "added task".to_string(),
                            },
                        ],
                    },
                    Section {
                        name: "Done".to_string(),
                        tasks: vec![],
                    },
                ],
            }],
            file_path: PathBuf::new(),
        };

        let mut actual = base.clone();
        actual.add("- added task", "Section 1").unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn add_task_new_section() {
        let base = Todo {
            days: vec![Day {
                date: today(),
                sections: vec![
                    Section {
                        name: "Section 1".to_string(),
                        tasks: vec![
                            Task {
                                text: "task 1".to_string(),
                            },
                            Task {
                                text: "task 2".to_string(),
                            },
                            Task {
                                text: "task 3".to_string(),
                            },
                        ],
                    },
                    Section {
                        name: "Done".to_string(),
                        tasks: vec![],
                    },
                ],
            }],
            file_path: PathBuf::new(),
        };

        let expected = Todo {
            days: vec![Day {
                date: today(),
                sections: vec![
                    Section {
                        name: "Section 1".to_string(),
                        tasks: vec![
                            Task {
                                text: "task 1".to_string(),
                            },
                            Task {
                                text: "task 2".to_string(),
                            },
                            Task {
                                text: "task 3".to_string(),
                            },
                        ],
                    },
                    Section {
                        name: "Done".to_string(),
                        tasks: vec![],
                    },
                    // new section is added to end of vec, not before Done
                    Section {
                        name: "New Section".to_string(),
                        tasks: vec![Task {
                            text: "added task".to_string(),
                        }],
                    },
                ],
            }],
            file_path: PathBuf::new(),
        };

        let mut actual = base.clone();
        actual.add("- added task", "New Section").unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn next_day() {
        let base = Todo {
            days: vec![Day {
                date: today() - ChronoDuration::days(1),
                sections: vec![
                    Section {
                        name: "Section 1".to_string(),
                        tasks: vec![
                            Task {
                                text: "task 1".to_string(),
                            },
                            Task {
                                text: "task 2".to_string(),
                            },
                        ],
                    },
                    Section {
                        name: "Done".to_string(),
                        tasks: vec![Task {
                            text: "task 3".to_string(),
                        }],
                    },
                ],
            }],
            file_path: PathBuf::new(),
        };

        let expected = Todo {
            days: vec![
                Day {
                    date: today() - ChronoDuration::days(1),
                    sections: vec![
                        Section {
                            name: "Section 1".to_string(),
                            tasks: vec![
                                Task {
                                    text: "task 1".to_string(),
                                },
                                Task {
                                    text: "task 2".to_string(),
                                },
                            ],
                        },
                        Section {
                            name: "Done".to_string(),
                            tasks: vec![Task {
                                text: "task 3".to_string(),
                            }],
                        },
                    ],
                },
                Day {
                    date: today(),
                    sections: vec![
                        Section {
                            name: "Section 1".to_string(),
                            tasks: vec![
                                Task {
                                    text: "task 1".to_string(),
                                },
                                Task {
                                    text: "task 2".to_string(),
                                },
                            ],
                        },
                        Section {
                            name: "Done".to_string(),
                            tasks: vec![],
                        },
                    ],
                },
            ],
            file_path: PathBuf::new(),
        };

        let mut actual = base.clone();

        actual.next_day();
        assert_eq!(actual, expected);
    }
}