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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//! Represention of a day as a set of times, entries, and durations.
//!
//! # Examples
//!
//! ```rust, no_run
//! use timelog::{Day, Entry, Result};
//!
//! # fn main() -> Result<()> {
//! # let entries: Vec<Entry> = vec![];
//! # let mut entry_iter = entries.into_iter();
//! let mut day = Day::new("2021-07-02")?;
//! while let Some(entry) = entry_iter.next() {
//!     day.add_entry(&entry);
//! }
//! day.finish()?;
//! print!("{}", day.detail_report());
//! #   Ok(())
//! #  }
//! ```
//!
//! # Description
//!
//! The [`Day`] type represents the entries of a particular day. It tracks projects and combines time
//! spent on the same task from multiple points in the day.
//!
//! [`Day`] also provides the ability to print various reports on the day's
//! activities.

#[doc(inline)]
use crate::chart::{
    BarGraph, ColorIter, DayHours, Legend, Percent, Percentages, PieChart, PieData
};
#[cfg(doc)]
use crate::date;
#[doc(inline)]
use crate::date::{Date, DateTime};
use crate::emit_xml;
#[doc(inline)]
use crate::error::Error;
#[doc(inline)]
use crate::entry::Entry;
use crate::Result;
use crate::TaskEvent;

use std::cmp::{Ordering, PartialOrd};
use std::collections::HashMap;
use std::fmt::{self, Display};
use std::io::Write;
use std::time::Duration;

use xml::writer::{EventWriter, XmlEvent};

use regex::Regex;

/// Type representing a day and all associated tasks
#[derive(Debug)]
pub struct Day {
    /// [`Date`] for today
    stamp: Date,
    /// Optional timestamp representing the start of entries for the day
    start: Option<DateTime>,
    /// Total [`Duration`] of all of the entries for the day
    dur: Duration,
    /// Map of tasks to task entries
    tasks: HashMap<String, TaskEvent>,
    /// Map of projects to task entries
    proj_dur: HashMap<String, Duration>,
    /// List of task entries
    entries: Vec<TaskEvent>,
    /// List of zero duration event entries
    events: Vec<Entry>,
    /// Optional start of most recent entry while parsing a day
    last_start: Option<DateTime>,
    /// Optional most recent entry
    last_entry: Option<Entry>,
}

/// Format duration information as a [`String`] of the form `M:SS`
pub fn format_dur(dur: &Duration) -> String {
    let secs = dur.as_secs() + 30; // force rounding
    format!("{:>2}:{:0>2}", (secs / 3600), (secs % 3600) / 60)
}

impl<'a> Day {
    /// Creates a [`Day`] struct that collects the entries for the date specified by
    /// the `stamp`.
    ///
    /// ## Errors
    ///
    /// - Return an [`Error::MissingDate`] if the string is empty.
    /// - Return an [`InvalidDate`](date::Error::InvalidDate) error if the `stamp` is not formatted
    /// as 'YYYY-MM-DD'.
    pub fn new(stamp: &str) -> Result<Self> {
        if stamp.is_empty() {
            return Err(Error::MissingDate);
        }
        Ok(Day {
            stamp: Date::try_from(stamp)?,
            start: None,
            dur: Duration::default(),
            tasks: HashMap::new(),
            proj_dur: HashMap::new(),
            entries: Vec::new(),
            events: Vec::new(),
            last_start: None,
            last_entry: None,
        })
    }

    /// Return the duration of the day in seconds
    pub fn duration_secs(&self) -> u64 { self.dur.as_secs() }

    /// Returns `true` only if no entries have been added to the day.
    pub fn is_empty(&self) -> bool { self.entries.is_empty() }

    /// Returns `true` only the day is complete.
    pub fn is_complete(&self) -> bool { self.last_start.is_none() }

    /// Return the date stamp for the day in 'YYYY-MM-DD' form.
    pub fn date_stamp(&self) -> String { self.stamp.into() }

    /// Return the date for the [`Day`] object in a [`Date`].
    pub fn date(&self) -> Date { self.stamp }

    /// Return an iterator over the project names for today
    pub fn projects(&self) -> impl Iterator<Item = &'_ str> {
        self.proj_dur.keys().map(|k| k.as_str())
    }

    /// Return an iterator over the events for today.
    pub fn events(&self) -> impl Iterator<Item = &'_ Entry> {
        self.events.iter()
    }

    // Update the task duration for most recent [`Entry`]
    fn update_task_duration(&mut self, prev: &Entry, dur: &Duration) {
        match self.tasks.get_mut(&prev.entry_text()) {
            Some(task) => task.add_dur(*dur),
            None => {
                let task = TaskEvent::new(prev.date_time(), prev.project(), *dur);
                self.tasks.insert(prev.entry_text(), task);
            },
        }
    }

    // Update the project duration for most recent entry
    fn update_project_duration(&mut self, proj: &str, dur: &Duration) {
        match self.proj_dur.get_mut(proj) {
            Some(proj_dur) => { *proj_dur += *dur; },
            None => { self.proj_dur.insert(proj.to_owned(), *dur); },
        }
    }

    /// Add an [`Entry`] to the current [`Day`].
    ///
    /// ## Errors
    ///
    /// - Return an [`EntryOrder`](date::Error::EntryOrder) error if the new entry is before the
    /// previous entry.
    pub fn add_entry(&mut self, entry: &Entry) -> Result<()> {
        if entry.is_event() {
            self.events.push(entry.clone());
        }
        else if !entry.is_ignore() {
            self.update_dur(&entry.date_time())?;
            self.start_task(entry);
            self.last_entry = (!entry.is_stop()).then(|| entry.clone());
        }
        Ok(())
    }

    /// Update the duration of the most recent task
    ///
    /// ## Errors
    ///
    /// - Return an [`EntryOrder`](date::Error::EntryOrder) error if the new entry is before the
    /// previous entry.
    pub fn update_dur(&mut self, date_time: &DateTime) -> Result<()> {
        if let Some(prev) = &self.last_entry.clone() {
            let curr_dur = date_time.sub(&prev.date_time())?;
            if !prev.entry_text().is_empty() {
                self.update_task_duration(prev, &curr_dur);
            }
            let prev_proj = prev.project().unwrap_or_default();
            self.update_project_duration(&prev_proj, &curr_dur);
            self.dur += curr_dur;
            if let Some(prev) = self.entries.last_mut() {
                prev.add_dur(curr_dur);
            }
        }
        Ok(())
    }

    /// Update the duration of the most recent task
    ///
    /// ## Errors
    ///
    /// - Return an [`EntryOrder`](date::Error::EntryOrder) error if the new entry is before the
    /// previous entry.
    pub fn finish(&mut self) -> Result<()> {
        if !self.is_complete() {
            let date = (self.date() == Date::today())
                .then(DateTime::now)
                .unwrap_or_else(|| self.stamp.day_end());
            self.update_dur(&date)?;
            self.last_start = None;
        }

        Ok(())
    }

    /// Start a day from previous day's last entry.
    ///
    /// ## Errors
    ///
    /// - Return an [`EntryOrder`](date::Error::EntryOrder) error if the new entry is before the
    /// previous entry.
    pub fn start_day(&mut self, entry: &Entry) -> Result<()> {
        if entry.is_start() {
            let entry = entry.clone();
            self.add_entry(&entry)?;
            self.last_start = Some(entry.date_time());
        }
        Ok(())
    }

    /// Initialize a new task item in the day based on the [`Entry`] object supplied in `event`.
    ///
    /// This method only starts a task if no previous matching task exists in the day.
    pub fn start_task(&mut self, entry: &Entry) {
        if entry.is_stop() {
            self.last_start = None;
            return;
        }
        let task = entry.entry_text();
        self.last_start = Some(entry.date_time());
        self.tasks.entry(task).or_insert_with(|| {
            TaskEvent::new(entry.date_time(), entry.project(), Duration::default())
        });
        self.entries.push(TaskEvent::new(
            entry.date_time(),
            entry.project(),
            Duration::default(),
        ));
    }

    // Format the stamp line to f with the supplied `separator`.
    fn _format_stamp_line(&self, f: &mut fmt::Formatter<'_>, sep: &str) -> fmt::Result {
        writeln!(f, "{}{} {}", self.date_stamp(), sep, format_dur(&self.dur))
    }

    // Format the project line to `f` with the supplied `separator`.
    fn _format_project_line(
        &self, f:&mut fmt::Formatter<'_>, proj: &str, dur: &Duration
    ) -> fmt::Result {
        writeln!(f, "  {:<13}{}", proj, format_dur(dur))
    }

    // Format the task line to `f` with the supplied `separator`.
    fn _format_task_line(
        &self, f:&mut fmt::Formatter<'_>, task: &str, dur: &Duration
    ) -> fmt::Result {
        match Entry::task_breakdown(task) {
            (Some(task), Some(detail)) => writeln!(f, "    {:<20}{} ({})", task, format_dur(dur), detail),
            (Some(task), None) => writeln!(f, "    {:<20}{}", task, format_dur(dur)),
            (None, Some(detail)) => writeln!(f, "    {:<20}{}", detail, format_dur(dur)),
            _ => writeln!(f, "    {:<20}{}", "", format_dur(dur)),
        }
    }

    /// Return a [`DetailReport`] from the current [`Day`].
    pub fn detail_report(&'a self) -> DetailReport<'a> { DetailReport(self) }

    /// Return a [`SummaryReport`] from the current [`Day`].
    pub fn summary_report(&'a self) -> SummaryReport<'a> { SummaryReport(self) }

    /// Return a [`HoursReport`] from the current [`Day`].
    pub fn hours_report(&'a self) -> HoursReport<'a> { HoursReport(self) }

    /// Return a [`HoursReport`] from the current [`Day`].
    pub fn event_report(&'a self) -> EventReport<'a> { EventReport(self) }

    /// Return a [`DailyChart`] from the current [`Day`].
    pub fn daily_chart(&'a self) -> DailyChart<'a> { DailyChart(self) }

    /// Return `true` if the day contains one or more tasks.
    pub fn has_tasks(&self) -> bool { !self.tasks.is_empty() }

    // Filter tasks by project, returning a HashMap.
    fn project_filtered_tasks(&self, filter: &Regex) -> HashMap<String, TaskEvent> {
        self.tasks
            .iter()
            .filter(|(_, t)| filter.is_match(&t.project()))
            .fold(HashMap::new(), |mut h, (k, t)| {
                h.insert(k.to_string(), t.clone());
                h
            })
    }

    // Return a [`HashMap`] of projects and [`Duration`]s that match the supplied [`Regex`]es.
    fn project_filtered_durs(&self, filter: &Regex) -> HashMap<String, Duration> {
        self.proj_dur
            .iter()
            .filter(|(k, _)| filter.is_match(k))
            .fold(HashMap::new(), |mut h, (k, v)| {
                h.insert(k.to_string(), *v);
                h
            })
    }

    /// Make a copy of the current [`Day`] object containing only the tasks associated
    /// with a supplied [`Regex`].
    pub fn filtered_by_project(&self, filter: &Regex) -> Self {
        let proj_durs = self.project_filtered_durs(filter);
        Self {
            stamp: self.stamp,
            start: self.start,
            dur: proj_durs.values().sum(),
            tasks: self.project_filtered_tasks(filter),
            entries: self.entries.clone(),  // TODO: Need to filter somehow
            events: self.events.clone(),
            proj_dur: proj_durs,
            last_start: self.start,
            last_entry: None,
        }
    }

    /// Return a [`Vec`] of tuples mapping project name to percentage of the overall
    /// time this project took.
    pub fn project_percentages(&'a self) -> Percentages {
        let mut pie = PieData::default();

        self.proj_dur.iter()
            .for_each(|(proj, dur)| pie.add_secs(proj.as_str(), dur.as_secs()));

        pie.percentages()
    }

    /// Return a [`Vec`] of tuples mapping the task name and percentage of the
    /// supplied project.
    pub fn task_percentages(&self, proj: &str) -> Percentages {
        let mut pie = PieData::default();

        self.tasks
            .iter()
            .filter(|(_t, tsk)| tsk.project() == proj)
            .for_each(|(t, tsk)| {
                let task = match Entry::task_breakdown(t) {
                    (None, None) => String::new(),
                    (Some(tname), None) => tname,
                    (None, Some(detail)) => format!(" ({})", detail),
                    (Some(tname), Some(detail)) => format!("{} ({})", tname, detail),
                };
                pie.add_secs(&task, tsk.as_secs());
            });

        pie.percentages()
    }

    // Return an iterator over the [`TaskEvents`] in the day.
    fn entries(&self) -> impl Iterator<Item = &'_ TaskEvent> { self.entries.iter() }
}

/// Representation of the full report about a [`Day`].
pub struct DetailReport<'a>(&'a Day);

impl<'a> Display for DetailReport<'a> {
    /// Format the [`Day`] information.
    ///
    /// The output starts with the current datestamp and duration for the day. Indented
    /// under that are individual projects. Individual tasks are indented under the
    /// projects.
    ///
    /// This is the most detailed report.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let day = self.0;
        let mut last_proj = String::new();
        writeln!(f)?;
        day._format_stamp_line(f, "")?;

        let mut tasks: Vec<(String, &String, &TaskEvent)> = day
            .tasks
            .iter()
            .map(|(t, tsk)| (tsk.project(), t, tsk))
            .collect();
        tasks.sort();

        for (cur_proj, tname, task) in tasks {
            if cur_proj != last_proj {
                day._format_project_line(
                    f,
                    &cur_proj,
                    day.proj_dur.get(&cur_proj).unwrap_or(&Duration::default()),
                )?;
                last_proj = cur_proj
            }
            day._format_task_line(f, tname, &task.duration())?;
        }
        Ok(())
    }
}

/// Representation of the summary report about a [`Day`].
pub struct SummaryReport<'a>(&'a Day);

impl<'a> Display for SummaryReport<'a> {
    /// Format the [`Day`] information.
    ///
    /// The output starts with the current datestamp and duration for the day. Indented
    /// under that are individual projects.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let day = self.0;

        let proj_dur = &day.proj_dur;
        let mut keys: Vec<&String> = proj_dur.keys().collect();
        keys.sort();

        day._format_stamp_line(f, "")?;
        for proj in keys {
            day._format_project_line(f, proj, proj_dur.get(proj).unwrap())?;
        }
        Ok(())
    }
}

/// Representation of the hours report about a [`Day`].
pub struct HoursReport<'a>(&'a Day);

impl<'a> Display for HoursReport<'a> {
    /// Format the [`Day`] information.
    ///
    /// The output only displays the current datestamp and duration for the day.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0._format_stamp_line(f, ":")
    }
}

/// Representation of the event report about a [`Day`].
pub struct EventReport<'a>(&'a Day);

impl<'a> Display for EventReport<'a> {
    /// Format the [`Day`] information.
    ///
    /// The output only displays the zero duration events associated with a [`Day`].
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "{}", self.0.date_stamp())?;
        if self.0.events().count() > 0usize {
            for ev in self.0.events() {
                writeln!(f, "  {}  {}", ev.date_time().hhmm(), ev.entry_text())?
            }
        }
        else {
            writeln!(f, "  No events found")?;
        }
        Ok(())
    }
}

/// Representation of chart report about a [`Day`].
pub struct DailyChart<'a>(&'a Day);

impl<'a> DailyChart<'a> {
    /// Return a [`Vec`] of tuples mapping project name to percentage of the overall
    /// time this project took.
    pub fn project_percentages(&self) -> Percentages { self.0.project_percentages() }

    /// Return a [`Vec`] of tuples mapping the task name and percentage of the
    /// supplied project.
    pub fn task_percentages(&self, proj: &str) -> Percentages { self.0.task_percentages(proj) }

    /// Write a pie chart representing the projects for the current day to the supplied
    /// [`EventWriter`].
    pub fn project_pie<W: Write>(&self, w: &mut EventWriter<W>) -> Result<()> {
        const R: f32 = 100.0;
        let legend = Legend::new(14.0, ColorIter::default());
        let pie = PieChart::new(R, legend);

        let mut percents = self.project_percentages();
        percents.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
        emit_xml!(w, div, class: "project" => {
            emit_xml!(w, h2; &format!("{} ({}) Projects", self.0.date_stamp(), self.0.date().weekday()))?;
            pie.write_pie(w, &percents)?;
            self.project_hours(w)
        })
    }

    /// Write a bar-graph representation of the tasks by hour in the current day to the supplied
    /// [`EventWriter`].
    pub fn project_hours<W: Write>(&self, w: &mut EventWriter<W>) -> Result<()> {
        emit_xml!(w, div, class: "hours" => {
            emit_xml!(w, h3; "Hourly")?;
            emit_xml!(w, div, class: "hist" => {
                let mut day_hours = DayHours::default();
                for entry in self.0.entries() {
                    day_hours.add(entry.clone());
                }
                let bar_graph = BarGraph::new(&self.project_percentages());
                bar_graph.write(w, &day_hours)
            })
        })
    }

    /// Write a pie chart representing the tasks for the supplied project to the supplied
    /// [`EventWriter`].
    pub fn task_pie<W: Write>(
        &self, w: &mut EventWriter<W>, proj: &str, percent: &Percent
    ) -> Result<()> {
        const R: f32 = 60.0;
        let legend = Legend::new(12.0, ColorIter::default());
        let pie = PieChart::new(R, legend);

        let mut percents = self.task_percentages(proj);
        percents.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
        emit_xml!(w, div => {
            emit_xml!(w, h3 => {
                emit_xml!(w; "Tasks for ")?;
                emit_xml!(w, em; &format!("{} ({})", proj, percent))
            })?;
            pie.write_pie(w, &percents)
        })
    }

    /// Write the charts for the current day to the supplied [`EventWriter`].
    pub fn write<W: Write>(&self, w: &mut EventWriter<W>) -> Result<()> {
        emit_xml!(w, div, class: "day" => {
            self.project_pie(w)?;
            emit_xml!(w, div, class: "tasks" => {
                let mut percentages = self.project_percentages();
                percentages.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
                for percent in percentages {
                    self.task_pie(w, percent.label(), percent.percent())?;
                }
                Ok(())
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chart::TagPercent;
    use crate::entry::Entry;
    use spectral::prelude::*;

    const INITIAL_ENTRIES: [(&str, u64); 8] = [
        ("+proj1 @Make changes", 0),
        ("+proj2 @Start work", 1),
        ("+proj1 @Make changes", 2),
        ("+proj1 @Stuff Other changes", 3),
        ("stop", 4),
        ("+proj1 @Stuff Other changes", 4),
        ("+proj1 @Final", 5),
        ("stop", 6),
    ];
    const MORE_ENTRIES: [(&str, u64); 4] = [
        ("+proj3 @Phone call", 60 + 0),
        ("+proj4 @Research", 60 + 1),
        ("@Phone call", 60 + 2),
        ("stop", 60 + 4),
    ];

    #[test]
    fn test_new_empty_stamp() {
        assert_that!(Day::new("")).is_err_containing(Error::MissingDate);
    }

    #[test]
    fn test_new_invalid_stamp() {
        assert_that!(Day::new("foo")).is_err_containing(&(crate::date::Error::InvalidDate).into());
    }

    #[test]
    fn test_update_dur() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        let _ = day.update_dur(&DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap());
        assert_that!(day.duration_secs()).is_equal_to(&0);
    }

    #[test]
    fn test_add_entry() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        let entry = Entry::from_line("2021-06-10 08:00:00 +proj1 do something").unwrap();
        let _ = day.add_entry(&entry);
        let entry = Entry::from_line("2021-06-10 08:45:00 stop").unwrap();
        let _ = day.add_entry(&entry);
        assert_that!(day.duration_secs()).is_equal_to(&(45 * 60));
    }

    #[test]
    fn test_format_dur() {
        assert_that!(format_dur(&Duration::default())).is_equal_to(&String::from(" 0:00"));
        assert_that!(format_dur(&Duration::from_secs(3600))).is_equal_to(&String::from(" 1:00"));
        assert_that!(format_dur(&Duration::from_secs(3629))).is_equal_to(&String::from(" 1:00"));
        assert_that!(format_dur(&Duration::from_secs(3630))).is_equal_to(&String::from(" 1:01"));
        assert_that!(format_dur(&Duration::from_secs(3660))).is_equal_to(&String::from(" 1:01"));
        assert_that!(format_dur(&Duration::from_secs(36000))).is_equal_to(&String::from("10:00"));
        assert_that!(format_dur(&Duration::from_secs(360000))).is_equal_to(&String::from("100:00"));
    }

    #[test]
    fn test_new_empty() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let day = day_result.unwrap();
        assert_that!(&day.is_empty()).is_true();
        assert_that!(&day.duration_secs()).is_equal_to(0u64);
        assert_that!(&day.is_complete()).is_true();
        assert_that!(&day.date_stamp()).is_equal_to(&String::from("2021-06-10"));
    }

    #[test]
    fn test_detail_report_empty() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let day = day_result.unwrap();
        let expect = String::from("\n2021-06-10  0:00\n");
        assert_that!(format!("{}", day.detail_report())).is_equal_to(expect);
    }

    #[test]
    fn test_summary_report_empty() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let day = day_result.unwrap();
        let detail = format!("{}", day.summary_report());
        let expected = String::from("2021-06-10  0:00\n");
        assert_that!(detail).is_equal_to(expected);
    }

    #[test]
    fn test_hours_report_empty() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let day = day_result.unwrap();
        let expect = String::from("2021-06-10:  0:00\n");
        assert_that!(format!("{}", day.hours_report())).is_equal_to(expect);
    }

    #[test]
    fn test_detail_report_with_one() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        let entry = Entry::from_line("2021-06-10 08:00:00 +foo @task").unwrap();
        let _ = day.add_entry(&entry);
        let stamp = entry.date_time();
        let _ = day.update_dur(&stamp.add(DateTime::minutes(45)).unwrap());
        let expect = String::from(
            "\n2021-06-10  0:45\n  foo           0:45\n    task                 0:45\n",
        );
        assert_that!(format!("{}", day.detail_report())).is_equal_to(expect);
    }

    fn add_entries(day: &mut Day) -> Result<()> {
        add_some_entries(
            day,
            DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap(),
            INITIAL_ENTRIES.iter()
        )?;
        day.finish()?;
        Ok(())
    }

    fn add_extra_entries(day: &mut Day) -> Result<()> {
        add_some_entries(
            day,
            DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap(),
            INITIAL_ENTRIES.iter().chain(MORE_ENTRIES.iter())
        )?;
        day.finish()?;
        Ok(())
    }

    fn add_some_entries<'b, I>(day: &mut Day, stamp: DateTime, entries: I) -> Result<()>
    where I: Iterator<Item = &'b (&'b str, u64)> {
        for (entry, mins) in entries {
            let ev = Entry::new(entry, stamp.add(DateTime::minutes(*mins)).unwrap());
            day.add_entry(&ev)?;
        }
        Ok(())
    }

    #[test]
    fn test_detail_report_tasks() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        add_entries(&mut day).expect("Entries out of order");

        let lines = [
            "\n",
            "2021-06-10  0:06\n",
            "  proj1         0:05\n",
            "    Final                0:01\n",
            "    Make                 0:02 (changes)\n",
            "    Stuff                0:02 (Other changes)\n",
            "  proj2         0:01\n",
            "    Start                0:01 (work)\n",
        ];
        let expect = lines.iter().fold(String::new(), |mut acc, s| {
            acc.push_str(s);
            acc
        });
        assert_that!(format!("{}", day.detail_report())).is_equal_to(expect);
    }

    #[test]
    fn test_summary_report_tasks() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        add_entries(&mut day).expect("Entries out of order");

        let lines = [
            "2021-06-10  0:06\n",
            "  proj1         0:05\n",
            "  proj2         0:01\n",
        ];

        let expected = lines.iter().fold(String::new(), |mut acc, s| {
            acc.push_str(s);
            acc
        });
        assert_that!(format!("{}", day.summary_report())).is_equal_to(expected);
    }

    #[test]
    fn test_project_percentages() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        add_extra_entries(&mut day).expect("Entries out of order");

        let expect: Percentages = vec![
            TagPercent::new("proj1", 50.0).unwrap(),
            TagPercent::new("", 20.0).unwrap(),
            TagPercent::new("proj2", 10.0).unwrap(),
            TagPercent::new("proj3", 10.0).unwrap(),
            TagPercent::new("proj4", 10.0).unwrap(),
        ];
        let mut actual = day.daily_chart().project_percentages();
        actual.sort_by(|lhs, rhs| lhs.partial_cmp(rhs).unwrap());
        assert_that!(actual).is_equal_to(expect);
    }

    #[test]
    fn test_task_percentages() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        add_extra_entries(&mut day).expect("Entries out of order");

        let expect: Percentages = vec![
            TagPercent::new("Make (changes)", 40.0).unwrap(),
            TagPercent::new("Stuff (Other changes)", 40.0).unwrap(),
            TagPercent::new("Final", 20.0).unwrap(),
        ];
        let mut actual = day.task_percentages("proj1");
        actual.sort_by(|lhs, rhs| lhs.partial_cmp(rhs).unwrap());
        assert_that!(actual).is_equal_to(expect);
    }

    #[test]
    fn test_hours_report_tasks() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        add_entries(&mut day).expect("Entries out of order");
        let expect = String::from("2021-06-10:  0:06\n");
        assert_that!(format!("{}", day.hours_report())).is_equal_to(expect);
    }

    #[test]
    fn test_project_filter_regex() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        add_entries(&mut day).expect("Entries out of order");
        let regex = Regex::new(r"^\w+1$").expect("Invalid project regex");
        let day2 = day.filtered_by_project(&regex);

        assert_that!(day2.proj_dur.len()).is_equal_to(&1);
        assert_that!(day2.proj_dur.contains_key("proj1")).is_true();

        let expected = String::from("2021-06-10  0:05\n  proj1         0:05\n");
        assert_that!(format!("{}", day2.summary_report())).is_equal_to(expected);
    }

    #[test]
    fn test_entries() {
        let day_result = Day::new("2021-06-10");
        assert_that!(&day_result).is_ok();

        let mut day = day_result.unwrap();
        add_extra_entries(&mut day).expect("Entries out of order");

        assert_that!(day.entries().count()).is_equal_to(9);
        let expected = [
            (DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap(), "proj1",  60),
            (DateTime::new((2021, 6, 10), (8, 1, 0)).unwrap(), "proj2",  60),
            (DateTime::new((2021, 6, 10), (8, 2, 0)).unwrap(), "proj1",  60),
            (DateTime::new((2021, 6, 10), (8, 3, 0)).unwrap(), "proj1",  60),
            (DateTime::new((2021, 6, 10), (8, 4, 0)).unwrap(), "proj1",  60),
            (DateTime::new((2021, 6, 10), (8, 5, 0)).unwrap(), "proj1",  60),
            (DateTime::new((2021, 6, 10), (9, 0, 0)).unwrap(), "proj3",  60),
            (DateTime::new((2021, 6, 10), (9, 1, 0)).unwrap(), "proj4",  60),
            (DateTime::new((2021, 6, 10), (9, 2, 0)).unwrap(), "", 120),
        ];
        for (ev, expect) in day.entries().zip(expected.iter()) {
            assert_that!(ev.start()).is_equal_to(&expect.0);
            assert_that!(ev.proj().unwrap_or_default()).is_equal_to(&expect.1.to_string());
            assert_that!(ev.as_secs()).is_equal_to(expect.2);
        }
    }

    #[test]
    fn test_day_crossing() {
        let mut day = Day::new("2021-06-10").unwrap();

        let line = "2021-06-10 23:20:00 +project Task";
        day.add_entry(&Entry::from_line(line).expect("Entry failed to parse"))
            .expect("Failed add");
        day.finish().expect("Unable to close day");
        let expected = r#"
2021-06-10  0:40
  project       0:40
    Task                 0:40
"#;
        let actual = format!("{}", day.detail_report());
        assert_that!(actual.as_str()).is_equal_to(expected);
    }
}