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
//! 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.

use std::collections::HashMap;
use std::fmt;
use std::time::Duration;

use regex::Regex;

#[doc(inline)]
use crate::chart::{Percentages, PieData};
#[cfg(doc)]
use crate::date;
#[doc(inline)]
use crate::date::{Date, DateTime};
#[doc(inline)]
use crate::entry::Entry;
#[doc(inline)]
use crate::error::Error;
use crate::Result;
use crate::TaskEvent;

pub mod report;

/// Representation of the full report about a [`Day`].
pub type DetailReport<'a> = report::DetailReport<'a>;
/// Representation of the summary report about a [`Day`].
pub type SummaryReport<'a> = report::SummaryReport<'a>;
/// Representation of the hours report about a [`Day`].
pub type HoursReport<'a> = report::HoursReport<'a>;
/// Representation of chart report about a [`Day`].
pub type DailyChart<'a> = report::DailyChart<'a>;
/// Representation of the event report about a [`Day`].
pub type EventReport<'a> = report::EventReport<'a>;

/// 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 `H:MM`
#[rustfmt::skip]
pub fn format_dur(dur: &Duration) -> String {
    const DAY: u64 = 24 * 60 * 60;
    const HOUR: u64 = 3600;
    const MINUTE: u64 = 60;

    let secs = dur.as_secs() + 30; // force rounding
    if secs > DAY {
        format!("{}d {:>2}:{:0>2}", secs / DAY, (secs % DAY) / HOUR, (secs % HOUR) / MINUTE)
    }
    else {
        format!("{:>2}:{:0>2}", (secs / HOUR), (secs % HOUR) / MINUTE)
    }
}

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 or events have been added to the day.
    pub fn is_empty(&self) -> bool { self.entries.is_empty() && self.events.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(String::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) {
        if let Some(task) =  self.tasks.get_mut(prev.entry_text()) {
            task.add_dur(*dur);
        }
        else {
            let proj = prev.project();
            let task = TaskEvent::new(prev.date_time(), proj, *dur);
            self.tasks.insert(prev.entry_text().to_string(), task);
        }
    }

    // Update the project duration for most recent entry
    #[rustfmt::skip]
    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_string(), *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);
        }
        else if !entry.is_ignore() {
            self.update_dur(&entry.date_time())?;
            self.start_task(&entry);
            self.last_entry = (!entry.is_stop()).then_some(entry);
        }
        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.diff(&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 stamp = entry.date_time();
            self.add_entry(entry.clone())?;
            self.last_start = Some(stamp);
        }
        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.to_string())
            .or_insert_with(|| TaskEvent::from_entry(entry));
        self.entries.push(TaskEvent::from_entry(entry));
    }

    // 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 {
        let fdur = format_dur(dur);
        match Entry::task_breakdown(task) {
            (Some(task), Some(detail)) => {
                writeln!(f, "    {task:<19} {fdur} ({detail})")
            }
            (Some(task), None) => writeln!(f, "    {task:<19} {fdur}"),
            (None, Some(detail)) => writeln!(f, "    {detail:<19} {fdur}"),
            _ => writeln!(f, "    {:<19} {}", "", fdur)
        }
    }

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

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

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

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

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

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

    /// Return `true` if the day contains one or more events.
    pub fn has_events(&self) -> bool { !self.events.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
            })
    }

    // Filter events by project, returning a HashMap.
    fn project_filtered_events(&self, filter: &Regex) -> Vec<Entry> {
        self.events
            .iter()
            .filter(|e| filter.is_match(e.project().unwrap_or_default()))
            .cloned()
            .collect()
    }

    // 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`].
    #[must_use]
    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.project_filtered_events(filter),
            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() }
}

#[cfg(test)]
pub(crate) mod tests {
    use spectral::prelude::*;

    use super::*;
    use crate::chart::TagPercent;
    use crate::entry::{Entry, EntryKind};

    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)
    ];
    #[rustfmt::skip]
    const SOME_EVENTS: [(&str, u64); 2] = [
        ("+foo thing1", 30),
        ("+foo thing2", 30 + 5)
    ];
    const MORE_ENTRIES: [(&str, u64); 4] = [
        ("+proj3 @Phone call", 60 + 0),
        ("+proj4 @Research", 60 + 1),
        ("@Phone call", 60 + 2),
        ("stop", 60 + 4)
    ];

    #[test]
    #[rustfmt::skip]
    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("4d  4:00"));
        assert_that!(format_dur(&Duration::from_secs(300000)))
            .is_equal_to(&String::from("3d 11:20"));
    }

    #[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"));
    }

    pub 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(())
    }

    pub fn add_some_events(day: &mut Day) -> Result<()> {
        let stamp = DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap();
        for (entry, mins) in SOME_EVENTS.iter() {
            let ev = Entry::new_marked(
                entry,
                stamp.add(DateTime::minutes(*mins)).unwrap(),
                EntryKind::Event
            );
            day.add_entry(ev)?;
        }
        day.finish()?;
        Ok(())
    }

    pub 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_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_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);
        #[rustfmt::skip]
        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);
        }
    }
}