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
//! Represention of a task event.
//!
//! # Examples
//!
//! ```rust
//! use std::time::Duration;
//! use timelog::{DateTime, TaskEvent};
//!
//! # fn main() {
//! let timestamp = DateTime::new((2022, 03, 14), (10, 0, 0)).expect("Invalid date or time");
//! let mut event = TaskEvent::new(
//!     timestamp,
//!     Some("project_1".into()),
//!     Duration::from_secs(300)
//!     );
//! println!("{}", event.project());
//! event.add_dur(Duration::from_secs(3000));
//! println!("{:?}", event.duration());
//! # }
//! ```
//!
//! # Description
//!
//! The [`TaskEvent`] type represents a single task event containing a
//! start time and duration.

#[doc(inline)]
use crate::date::DateTime;

use std::time::Duration;

/// Structure representing a single task event.
#[derive(Debug, Clone, Eq, Ord, PartialOrd, PartialEq)]
pub struct TaskEvent {
    /// Timestamp of the start of this event
    start: DateTime,
    /// Optional [`String`] representing the project
    proj: Option<String>,
    /// Calculated total [`Duration`] of the event
    dur: Duration,
}

impl TaskEvent {
    /// Create a [`TaskEvent`] with the supplied parameters.
    pub fn new(start: DateTime, proj: Option<String>, dur: Duration) -> Self {
        Self { start, proj, dur }
    }

    /// Return a tuple with two [`TaskEvent`]s, split at the supplied [`Duration`].
    /// The first starts at the same starting point as this [`TaskEvent`] and
    /// stopping at the supplied [`Duration`]. The second starts [`Duration`] after
    /// the start, containg the rest of the time.
    pub fn split(&self, dur: Duration) -> Option<(Self, Self)> {
        Some((
            Self {
                start: self.start,
                proj: self.proj(),
                dur
            },
            Self {
                start: self.start.add(dur).ok()?,
                proj: self.proj(),
                dur: self.dur - dur
            }
        ))
    }

    /// Return the project as a String if one exists.
    pub fn proj(&self) -> Option<String> { self.proj.as_ref().map(|p| p.to_string()) }

    /// Return the project as a String defaulting to an empty string.
    pub fn project(&self) -> String { self.proj().unwrap_or_default() }

    /// Return the hour of the start time.
    pub fn hour(&self) -> usize { self.start.hour() as usize }

    /// Return the starting [`DateTime`].
    pub fn start(&self) -> &DateTime { &self.start }

    /// Extend the [`TaskEvent`]'s duration by the supplied amount.
    pub fn add_dur(&mut self, dur: Duration) { self.dur += dur; }

    /// Return the [`Duration`] of this [`TaskEvent`].
    pub fn duration(&self) -> Duration { self.dur }

    /// Return the number of seconds this [`TaskEvent`] has lasted.
    pub fn as_secs(&self) -> u64 { self.dur.as_secs() }

    /// Return the number of seconds after the hour of the starting time.
    pub fn second_offset(&self) -> u32 { self.start.second_offset() }
}

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

    use crate::DateTime;

    #[test]
    fn test_new_with_project() {
        let task = TaskEvent::new(
            DateTime::new((2022, 3, 20), (12, 34, 56)).expect("Failed to create DateTime"),
            Some("proja".to_string()),
            Duration::from_secs(305)
        );
        assert_that!(task.proj()).is_some().contains(String::from("proja").as_str());
        assert_that!(task.project()).is_equal_to(String::from("proja"));
        assert_that!(task.start())
            .is_equal_to(&DateTime::new((2022, 3, 20), (12, 34, 56)).expect("Failed to create DateTime"));
        assert_that!(task.hour()).is_equal_to(12);
        assert_that!(task.duration()).is_equal_to(&Duration::from_secs(305));
    }

    #[test]
    fn test_new_without_project() {
        let task = TaskEvent::new(
            DateTime::new((2022, 3, 20), (13, 24, 56)).expect("Failed to create DateTime"),
            None,
            Duration::from_secs(255)
        );
        assert_that!(task.proj()).is_none();
        assert_that!(task.project()).is_equal_to(String::new());
        assert_that!(task.start())
            .is_equal_to(&DateTime::new((2022, 3, 20), (13, 24, 56)).expect("Failed to create DateTime"));
        assert_that!(task.hour()).is_equal_to(13);
        assert_that!(task.duration()).is_equal_to(&Duration::from_secs(255));
    }

    #[test]
    fn test_add_dur() {
        let mut task = TaskEvent::new(
            DateTime::new((2022, 3, 20), (12, 34, 56)).expect("Failed to create DateTime"),
            Some("proja".to_string()),
            Duration::from_secs(305)
        );

        assert_that!(task.as_secs()).named("Initial value").is_equal_to(305);

        task.add_dur(Duration::from_secs(3600));
        assert_that!(task.as_secs()).named("After add_dur").is_equal_to(3905);
        assert_that!(task.duration()).is_equal_to(Duration::from_secs(3905));
    }

    #[test]
    fn test_second_offset() {
        let task = TaskEvent::new(
            DateTime::new((2022, 3, 20), (12, 34, 56)).expect("Failed to create DateTime"),
            Some("proja".to_string()),
            Duration::from_secs(305)
        );

        assert_that!(task.second_offset()).is_equal_to(34 * 60 + 56);
    }

    #[test]
    fn test_split() {
        let task = TaskEvent::new(
            DateTime::new((2022, 3, 20), (12, 34, 56)).expect("Failed to create DateTime"),
            Some("proja".to_string()),
            Duration::from_secs(600)
        );

        let pair = task.split(Duration::from_secs(250));
        assert_that!(pair).is_some();
        let (first, second) = pair.unwrap();

        assert_that!(first.start()).is_equal_to(
            &DateTime::new((2022, 3, 20), (12, 34, 56)).expect("Failed to create DateTime")
        );
        assert_that!(first.duration()).is_equal_to(Duration::from_secs(250));

        assert_that!(second.start()).is_equal_to(
            &DateTime::new((2022, 3, 20), (12, 39, 6)).expect("Failed to create DateTime")
        );
        assert_that!(second.duration()).is_equal_to(Duration::from_secs(350));
    }
}