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
use std::{
    fmt::{Display, Formatter},
    str::FromStr,
    time::Duration,
};

use crate::error::{ActivityLogErrorKind, PaceErrorKind, PaceOptResult, PaceResult};
use chrono::{DateTime, Local, NaiveDateTime, NaiveTime, SubsecRound, TimeZone};
use serde_derive::{Deserialize, Serialize};

pub enum TimeFrame {
    Custom {
        start: DateTime<Local>,
        end: DateTime<Local>,
    },
    Daily,
    DaysInThePast(u32),
    Monthly,
    MonthsInThePast(u32),
    Weekly,
    WeeksInThePast(u32),
    Yearly,
    YearsInThePast(u32),
}

/// Converts timespec to nice readable relative time string
///
/// # Arguments
///
/// * `initial_time` - The initial time to calculate the relative time from
///
/// # Returns
///
/// A string representing the relative time from the initial time
pub fn duration_to_str(initial_time: DateTime<Local>) -> String {
    let now = Local::now();
    let delta = now.signed_duration_since(initial_time);

    let delta = (
        delta.num_days(),
        delta.num_hours(),
        delta.num_minutes(),
        delta.num_seconds(),
    );

    match delta {
        (days, ..) if days > 5 => format!("{}", initial_time.format("%b %d, %Y")),
        (days @ 2..=5, ..) => format!("{days} days ago"),
        (1, ..) => "one day ago".to_string(),

        (_, hours, ..) if hours > 1 => format!("{hours} hours ago"),
        (_, 1, ..) => "an hour ago".to_string(),

        (_, _, minutes, _) if minutes > 1 => format!("{minutes} minutes ago"),
        (_, _, 1, _) => "one minute ago".to_string(),

        (_, _, _, seconds) if seconds > 0 => format!("{seconds} seconds ago"),
        _ => "just now".to_string(),
    }
}

/// Extracts time from the given string or returns the current time
///
/// # Arguments
///
/// * `time` - The time to extract or None
///
/// # Errors
///
/// [`chrono::ParseError`] - If the time cannot be parsed
///
/// # Returns
///
/// A tuple containing the time and date
pub fn extract_time_or_now(time: &Option<String>) -> PaceResult<NaiveDateTime> {
    Ok(if let Some(ref time) = time {
        NaiveDateTime::new(
            Local::now().date_naive(),
            NaiveTime::parse_from_str(time, "%H:%M")?,
        )
    } else {
        // if no time is given, use the current time
        Local::now().naive_local().round_subsecs(0)
    })
}

/// Parses time from user input
///
/// # Arguments
///
/// * `time` - The time to parse
///
/// # Errors
///
/// [`PaceErrorKind::ParsingTimeFromUserInputFailed`] - If the time cannot be parsed
///
/// # Returns
///
/// The parsed time or None
pub fn parse_time_from_user_input(time: &Option<String>) -> PaceOptResult<NaiveDateTime> {
    time.as_ref()
        .map(|time| -> PaceResult<NaiveDateTime> {
            let Ok(time) = NaiveTime::parse_from_str(time, "%H:%M") else {
                return Err(PaceErrorKind::ParsingTimeFromUserInputFailed(time.clone()).into());
            };

            Ok(NaiveDateTime::new(Local::now().date_naive(), time))
        })
        .transpose()
}

/// The duration of an activity
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct PaceDuration(u64);

impl FromStr for PaceDuration {
    type Err = ActivityLogErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.parse::<u64>() {
            Ok(duration) => Ok(Self(duration)),
            _ => Err(ActivityLogErrorKind::ParsingDurationFailed(s.to_string())),
        }
    }
}

impl From<Duration> for PaceDuration {
    fn from(duration: Duration) -> Self {
        Self(duration.as_secs())
    }
}

impl From<chrono::Duration> for PaceDuration {
    fn from(duration: chrono::Duration) -> Self {
        Self(
            duration
                .num_seconds()
                .try_into()
                .expect("Can't convert chrono duration to pace duration"),
        )
    }
}

/// Wrapper for the start time of an activity to implement default
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Eq, PartialEq)]
pub struct BeginDateTime(NaiveDateTime);

impl BeginDateTime {
    pub fn new(time: NaiveDateTime) -> Self {
        Self(time)
    }

    /// Convert to a naive date time
    pub fn naive_date_time(&self) -> NaiveDateTime {
        self.0
    }

    pub fn and_local_timezone<Tz: TimeZone>(&self, tz: Tz) -> chrono::LocalResult<DateTime<Tz>> {
        self.0.and_local_timezone(tz)
    }
}

impl Display for BeginDateTime {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        <NaiveDateTime as Display>::fmt(&self.0, f)
    }
}

// Default BeginTime to now
impl Default for BeginDateTime {
    fn default() -> Self {
        Self(Local::now().naive_local().round_subsecs(0))
    }
}

impl From<NaiveDateTime> for BeginDateTime {
    fn from(time: NaiveDateTime) -> Self {
        Self(time)
    }
}

impl From<Option<NaiveDateTime>> for BeginDateTime {
    fn from(time: Option<NaiveDateTime>) -> Self {
        match time {
            Some(time) => Self(time),
            None => Self::default(),
        }
    }
}

/// Calculate the duration of the activity
///
/// # Arguments
///
/// * `end` - The end date and time of the activity
///
/// # Errors
///
/// Returns an error if the duration can't be calculated or is negative
///
/// # Returns
///
/// Returns the duration of the activity
pub fn calculate_duration(begin: &BeginDateTime, end: NaiveDateTime) -> PaceResult<PaceDuration> {
    let duration = end
        .signed_duration_since(begin.naive_date_time())
        .to_std()?;

    Ok(duration.into())
}

#[cfg(test)]
mod tests {

    use chrono::NaiveDate;

    use super::*;

    #[test]
    fn test_duration_to_str_passes() {
        let initial_time = Local::now();
        let result = duration_to_str(initial_time);
        assert_eq!(result, "just now");
    }

    #[test]
    fn test_extract_time_or_now_passes() {
        let time = Some("12:00".to_string());
        let result = extract_time_or_now(&time).expect("Time extraction failed");
        assert_eq!(
            result,
            NaiveDateTime::new(
                Local::now().date_naive(),
                NaiveTime::from_hms_opt(12, 0, 0).expect("Invalid date"),
            )
        );
    }

    #[test]
    fn test_parse_time_from_user_input_passes() {
        let time = Some("12:00".to_string());
        let result = parse_time_from_user_input(&time).expect("Time parsing failed");
        assert_eq!(
            result,
            Some(NaiveDateTime::new(
                Local::now().date_naive(),
                NaiveTime::from_hms_opt(12, 0, 0).expect("Invalid date"),
            ))
        );
    }

    #[test]
    fn test_calculate_duration_passes() {
        let begin = BeginDateTime::new(NaiveDateTime::new(
            NaiveDate::from_ymd_opt(2021, 1, 1).expect("Invalid date"),
            NaiveTime::from_hms_opt(0, 0, 0).expect("Invalid date"),
        ));
        let end = NaiveDateTime::new(
            NaiveDate::from_ymd_opt(2021, 1, 1).expect("Invalid date"),
            NaiveTime::from_hms_opt(0, 0, 1).expect("Invalid date"),
        );

        let duration = calculate_duration(&begin, end).expect("Duration calculation failed");
        assert_eq!(duration, Duration::from_secs(1).into());
    }

    #[test]
    fn test_calculate_duration_fails() {
        let begin = BeginDateTime::new(NaiveDateTime::new(
            NaiveDate::from_ymd_opt(2021, 1, 1).expect("Invalid date"),
            NaiveTime::from_hms_opt(0, 0, 1).expect("Invalid date"),
        ));
        let end = NaiveDateTime::new(
            NaiveDate::from_ymd_opt(2021, 1, 1).expect("Invalid date"),
            NaiveTime::from_hms_opt(0, 0, 0).expect("Invalid date"),
        );

        let duration = calculate_duration(&begin, end);
        assert!(duration.is_err());
    }

    #[test]
    fn test_pace_duration_from_duration_passes() {
        let duration = Duration::from_secs(1);
        let result = PaceDuration::from(duration);
        assert_eq!(result, PaceDuration(1));
    }

    #[test]
    fn test_pace_duration_from_chrono_duration_passes() {
        let duration = chrono::Duration::seconds(1);
        let result = PaceDuration::from(duration);
        assert_eq!(result, PaceDuration(1));
    }

    #[test]
    fn test_begin_date_time_new_passes() {
        let time = NaiveDateTime::new(
            NaiveDate::from_ymd_opt(2021, 1, 1).expect("Invalid date"),
            NaiveTime::from_hms_opt(0, 0, 0).expect("Invalid date"),
        );
        let result = BeginDateTime::new(time);
        assert_eq!(result, BeginDateTime(time));
    }

    #[test]
    fn test_begin_date_time_naive_date_time_passes() {
        let time = NaiveDateTime::new(
            NaiveDate::from_ymd_opt(2021, 1, 1).expect("Invalid date"),
            NaiveTime::from_hms_opt(0, 0, 0).expect("Invalid date"),
        );
        let begin_date_time = BeginDateTime::new(time);
        let result = begin_date_time.naive_date_time();
        assert_eq!(result, time);
    }

    #[test]
    fn test_begin_date_time_default_passes() {
        let result = BeginDateTime::default();
        assert_eq!(
            result,
            BeginDateTime(Local::now().naive_local().round_subsecs(0))
        );
    }

    #[test]
    fn test_begin_date_time_from_naive_date_time_passes() {
        let time = NaiveDateTime::new(
            NaiveDate::from_ymd_opt(2021, 1, 1).expect("Invalid date"),
            NaiveTime::from_hms_opt(0, 0, 0).expect("Invalid date"),
        );
        let result = BeginDateTime::from(time);
        assert_eq!(result, BeginDateTime(time));
    }

    #[test]
    fn test_pace_duration_default_passes() {
        let result = PaceDuration::default();
        assert_eq!(result, PaceDuration(0));
    }
}