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
//! Utilities for working with dates and times
//!
//! # Examples
//!
//! ```rust
//! use timelog::date::{Date, DateTime};
//! use timelog::Result;
//!
//! # fn main() -> Result<()> {
//! let mut day = Date::try_from("2021-07-02")?;
//! print!("Date: {}", day);
//!
//! let mut stamp = DateTime::try_from("2021-07-02 12:34:00")?;
//! print!("Stamp: {}", stamp);
//!
//! let mut today = Date::parse("today")?;
//! print!("Today: {}", today);
//! #   Ok(())
//! #  }
//! ```
//!
//! # Description
//!
//! The [`Date`] struct represents a date in the local time zone. The module also
//! provides tools for manipulating [`Date`]s.
//!
//! The [`DateTime`] struct represents a date and time in the local time zone. The
//! module also provides tools for manipulating [`DateTime`]s.

use std::cmp::{Eq, Ord, PartialEq, PartialOrd};
use std::convert::From;
use std::fmt::{self, Display};
use std::time::Duration;

use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike, Weekday};
use chrono::{Local, LocalResult, TimeZone};
use thiserror::Error;

/// Representation of a date in the local time zone.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
pub struct Date(chrono::Date<Local>);

/// Representation of a date and time in the local time zone.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
pub struct DateTime(chrono::DateTime<Local>);

/// Errors related to dates and times.
#[derive(Error, Debug, PartialEq)]
pub enum Error {
    /// Invalid day specification
    #[error("'{0}' is not a valid day specification")]
    InvalidDaySpec(String),

    /// Invalid stamp format on an event line.
    #[error("Invalid stamp format.")]
    InvalidDate,

    /// Entry line is encountered that is before a previous entry line.
    #[error("Entries out of order.")]
    EntryOrder,
}

/// Result type for errors in date functionality.
pub type Result<T> = std::result::Result<T, Error>;

// Convert weekday string into appropriate Weekday variant.
fn weekday_from_str(day: &str) -> Result<Weekday> {
    match day {
        "sunday" => Ok(Weekday::Sun),
        "monday" => Ok(Weekday::Mon),
        "tuesday" => Ok(Weekday::Tue),
        "wednesday" => Ok(Weekday::Wed),
        "thursday" => Ok(Weekday::Thu),
        "friday" => Ok(Weekday::Fri),
        "saturday" => Ok(Weekday::Sat),
        _ => Err(Error::InvalidDaySpec(day.to_owned())),
    }
}

// Convert Weekday variabt into appropriate weekday string.
fn weekday_str(day: Weekday) -> &'static str {
    match day {
        Weekday::Sun => "Sunday",
        Weekday::Mon => "Monday",
        Weekday::Tue => "Tuesday",
        Weekday::Wed => "Wednesday",
        Weekday::Thu => "Thursday",
        Weekday::Fri => "Friday",
        Weekday::Sat => "Saturday",
    }
}

impl Date {
    /// Create a [`Date`] out of a year, month, and day, returning a [`Result`].
    ///
    /// ## Errors
    ///
    /// If one of the parameters is outside the legal range for a date, returns an
    /// [`Error::InvalidDate`].
    pub fn new(year: u32, month: u32, day: u32) -> Result<Self> {
        match Local.ymd_opt(year as i32, month, day) {
            LocalResult::Single(d) => Ok(Self(d)),
            _ => Err(Error::InvalidDate),
        }
    }

    /// Create a [`Date`] for today.
    pub fn today() -> Self { Self(Local::today()) }

    // Find the last date before this one where the day of the week was
    // weekday.
    fn find_previous(&self, weekday: Weekday) -> Self {
        let mut day = self.0.pred();
        while day.weekday() != weekday {
            day = day.pred();
        }
        Self(day)
    }

    /// Create a [`Date`] object from the supplied date specification.
    ///
    /// Legal specifications include "today" and "yesterday", the days of the week "sunday"
    /// through "saturday", and a date in the form "YYYY-MM-DD".
    /// The days of the week result in the date representing the previous instance of that day
    /// (last Monday for "monday", etc.).
    ///
    /// ## Errors
    ///
    /// Return [`Error::InvalidDaySpec`] if the supplied spec is not valid.
    pub fn parse(datespec: &str) -> Result<Self> {
        match datespec {
            "today" => Ok(Self::today()),
            "yesterday" => Ok(Self::today().pred()),
            "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" => {
                Ok(Self::today().find_previous(weekday_from_str(datespec)?))
            },
            _ => Self::try_from(datespec),
        }
    }

    /// Create a [`DateTime`] object for the last second of the current [`Date`]
    pub fn day_end(&self) -> DateTime { DateTime(self.0.and_hms(23, 59, 59)) }

    /// Create a [`DateTime`] object for the first second of the current [`Date`]
    pub fn day_start(&self) -> DateTime { DateTime(self.0.and_hms(0, 0, 0)) }

    /// Create a [`Date`] for the day after the current date.
    pub fn succ(&self) -> Date { Self(self.0.succ()) }

    /// Create a [`Date`] for the day before the current date.
    pub fn pred(&self) -> Date { Self(self.0.pred()) }

    /// Return the year portion of the [`Date`]
    pub fn year(&self) -> u32 { self.0.year() as u32 }

    /// Return the month portion of the [`Date`]
    pub fn month(&self) -> u32 { self.0.month() }

    /// Return the day portion of the [`Date`]
    pub fn day(&self) -> u32 { self.0.day() }

    /// Return the day of the week as a string.
    pub fn weekday(&self) -> &'static str { weekday_str(self.0.weekday()) }
}

impl std::convert::TryFrom<&str> for Date {
    type Error = Error;

    /// Create a [`Date`] out of a string, returning a [`Result`]
    ///
    /// ## Errors
    ///
    /// If the date is not formatted as 'YYYY-MM-DD', returns an [`Error::InvalidDate`].
    /// Also if the date string cannot be converted into a [`Date`], returns an
    /// [`Error::InvalidDate`].
    fn try_from(date: &str) -> Result<Self> {
        let parsed: NaiveDate =
            NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| Error::InvalidDate)?;
        Ok(Self(Local.from_local_date(&parsed).single().ok_or(Error::InvalidDate)?))
    }
}

impl Display for Date {
    /// Format a [`Date`] object in "YYYY-MM-DD" format.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{:02}-{:02}", self.0.year(), self.0.month(), self.0.day())
    }
}

impl From<Date> for String {
    /// Convert a [`Date`] into a [`String`]
    fn from(date: Date) -> Self { date.to_string() }
}

impl DateTime {
    /// Create a [`DateTime`] from two tuples, one representing the date (year, month, day) and
    /// the second representing the time (hour, minute, second).
    ///
    /// ## Errors
    ///
    /// Return an [`Error::InvalidDate`] if the values in the tuples are not appropriate for the
    /// data types.
    pub fn new(date: (u32, u32, u32), time: (u32, u32, u32)) -> Result<Self> {
        let dt = match Local.ymd_opt(date.0 as i32, date.1, date.2) {
            LocalResult::Single(d) => d
                .and_hms_opt(time.0, time.1, time.2)
                .ok_or(Error::InvalidDate)?,
            _ => return Err(Error::InvalidDate),
        };
        Ok(Self(dt))
    }

    /// Return the epoch time representing the current value of the [`DateTime`] object.
    pub fn timestamp(&self) -> i64 { self.0.timestamp() }

    /// Return a copy of just the [`Date`] portion of the [`DateTime`] object.
    pub fn date(&self) -> Date { Date(self.0.date()) }

    /// Create a [`Date`] for right now.
    pub fn now() -> Self { Self(Local::now()) }

    /// Return the hour of the day.
    pub fn hour(&self) -> u32 { self.0.hour() }

    /// Return the number of seconds after the hour.
    pub fn second_offset(&self) -> u32 { self.0.minute() * 60 + self.0.second() }

    /// Return the [`Duration`] as a [`Result`] resulting from subtracting the `rhs` from the
    /// object.
    ///
    /// ## Errors
    ///
    /// Return an [`Error::EntryOrder`] if the `rhs` is larger than the [`DateTime`].
    pub fn sub(&self, rhs: &Self) -> Result<Duration> {
        (self.0 - rhs.0).to_std().map_err(|_| Error::EntryOrder)
    }

    /// Return a [`DateTime`] as a [`Result`] resulting from adding the `rhs` [`Duration`] to the
    /// object.
    ///
    /// ## Errors
    ///
    /// Return an [`Error::InvalidDate`] if adding the duration results in a bad date.
    pub fn add(&self, rhs: Duration) -> Result<Self> {
        Ok(Self(
            self.0 + chrono::Duration::from_std(rhs).map_err(|_| Error::InvalidDate)?,
        ))
    }

    /// Return a [`Duration`] lasting the supplied number of minutes.
    pub fn seconds(seconds: u64) -> Duration { Duration::from_secs(seconds) }

    /// Return a [`Duration`] lasting the supplied number of minutes.
    pub fn minutes(minutes: u64) -> Duration { Duration::from_secs(minutes * 60) }

    /// Return a [`Duration`] lasting the supplied number of hours.
    pub fn hours(hours: u64) -> Duration { Duration::from_secs(hours * 3600) }

    /// Return a [`Duration`] lasting the supplied number of days.
    pub fn days(days: u64) -> Duration { Duration::from_secs(days * 86400) }

    /// Return a [`Duration`] lasting the supplied number of weeks.
    pub fn weeks(weeks: u64) -> Duration { Self::days(weeks * 7) }

    /// Return the formatted time as a [`String`]
    pub fn hhmm(&self) -> String {
        format!("{:02}:{:02}", self.0.hour(), self.0.minute())
    }
}

impl std::convert::TryFrom<&str> for DateTime {
    type Error = Error;

    /// Parse the [`DateTime`] out of a string, returning a [`Result`]
    ///
    /// ## Errors
    ///
    /// If the datetime is not formatted as 'YYYY-MM-DD HH:MM:SS', returns an
    /// [`Error::InvalidDate`]. Also if the datetime cannot be converted into a [`DateTime`],
    /// returns an [`Error::InvalidDate`].
    fn try_from(datetime: &str) -> Result<Self> {
        let parsed: NaiveDateTime = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S")
            .map_err(|_| Error::InvalidDate)?;
        Ok(Self(
            Local.from_local_datetime(&parsed).single().ok_or(Error::InvalidDate)?
        ))
    }
}

impl Display for DateTime {
    /// Format a [`DateTime`] object in "YYYY-MM-DD HH:MM:DD" format.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{:02}-{:02} {:02}:{:02}:{:02}",
            self.0.year(), self.0.month(), self.0.day(),
            self.0.hour(), self.0.minute(), self.0.second())
    }
}

impl From<DateTime> for String {
    /// Convert a [`Date`] into a [`String`]
    fn from(datetime: DateTime) -> Self { datetime.to_string() }
}

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

    #[test]
    fn test_date_new() {
        let date = Date::new(2021, 11, 20);
        assert_that!(&date).is_ok();
        assert_that!(date.unwrap().to_string()).is_equal_to(&String::from("2021-11-20"));
    }

    #[test]
    fn test_date_new_bad_month() {
        assert_that!(Date::new(2021, 0, 20)).is_err_containing(&Error::InvalidDate);
        assert_that!(Date::new(2021, 13, 20)).is_err_containing(&Error::InvalidDate);
    }

    #[test]
    fn test_date_new_bad_day() {
        assert_that!(Date::new(2021, 11, 0)).is_err_containing(&Error::InvalidDate);
        assert_that!(Date::new(2021, 11, 32)).is_err_containing(&Error::InvalidDate);
    }

    #[test]
    fn test_date_parse_today() {
        assert_that!(Date::parse("today"))
            .is_ok()
            .is_equal_to(&Date::today());
    }

    #[test]
    fn test_date_parse_yesterday() {
        assert_that!(Date::parse("yesterday"))
            .is_ok()
            .is_equal_to(&Date::today().pred());
    }

    #[test]
    fn test_date_parse_weekdays() {
        let max_dur = DateTime::days(7);
        let days: [&str; 7] = [
            "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"
        ];
        let today = Date::today();
        let midnight = Date::today().day_end();
        days.iter().for_each(|&day| {
            let date = Date::parse(day);
            assert_that!(date).is_ok().is_less_than(&today);

            let end_of_date = date.unwrap().day_end();
            assert_that!(midnight.sub(&end_of_date))
                .is_ok()
                .is_less_than_or_equal_to(&max_dur);
        });
    }

    #[test]
    fn test_date_day_end() {
        let date = Date::new(2021, 11, 20).unwrap();
        assert_that!(date.day_end())
            .is_equal_to(&DateTime::new((2021, 11, 20), (23, 59, 59)).unwrap());
    }

    #[test]
    fn test_date_day_start() {
        let date = Date::new(2021, 11, 20).unwrap();
        assert_that!(date.day_start())
            .is_equal_to(&DateTime::new((2021, 11, 20), (0, 0, 0)).unwrap());
    }

    #[test]
    fn test_date_succ() {
        let date = Date::new(2021, 11, 20).unwrap();
        assert_that!(date.succ()).is_equal_to(&Date::new(2021, 11, 21).unwrap());
    }

    #[test]
    fn test_date_pred() {
        let date = Date::new(2021, 11, 20).unwrap();
        assert_that!(date.pred()).is_equal_to(&Date::new(2021, 11, 19).unwrap());
    }

    #[test]
    fn test_date_try_from() {
        let date = Date::try_from("2021-11-20");
        assert_that!(&date).is_ok();
        assert_that!(date.unwrap()).is_equal_to(&Date::new(2021, 11, 20).unwrap());
    }

    #[test]
    fn test_date_try_from_bad() {
        let date = Date::try_from("fred");
        assert_that!(&date).is_err();
    }

    #[test]
    fn test_datetime_new() {
        let date = DateTime::new((2021, 11, 20), (11, 32, 18));
        assert_that!(date).is_ok();
        assert_that!(date.unwrap().to_string()).is_equal_to(&String::from("2021-11-20 11:32:18"));
    }

    #[test]
    fn test_datetime_new_bad_date() {
        let date = DateTime::new((2021, 13, 20), (11, 32, 18));
        assert_that!(date).is_err();
    }

    #[test]
    fn test_datetime_new_bad_time() {
        let date = DateTime::new((2021, 11, 20), (11, 82, 18));
        assert_that!(date).is_err();
    }

    #[test]
    fn test_datetime_try_from() {
        let date = DateTime::try_from("2021-11-20 11:32:18");
        assert_that!(&date).is_ok();
        assert_that!(date)
            .is_ok()
            .is_equal_to(&DateTime::new((2021, 11, 20), (11, 32, 18)).unwrap());
    }

    #[test]
    fn test_datetime_sub() {
        let date = DateTime::new((2021, 11, 20), (11, 32, 18)).unwrap();
        let old = DateTime::new((2021, 11, 18), (12, 00, 00)).unwrap();
        assert_that!(date.sub(&old))
            .is_ok()
            .is_equal_to(&Duration::from_secs(2 * 86400 - 28 * 60 + 18));
    }

    #[test]
    fn test_datetime_sub_bad() {
        let date = DateTime::new((2021, 11, 18), (12, 00, 00)).unwrap();
        let old  = DateTime::new((2021, 11, 20), (11, 32, 18)).unwrap();
        assert_that!(date.sub(&old)).is_err();
    }

    #[test]
    fn test_datetime_add_time() {
        let date = DateTime::new((2021, 11, 18), (12, 00, 00)).unwrap();
        let new = date.add(DateTime::minutes(10));
        assert_that!(new)
            .is_ok()
            .is_equal_to(&DateTime::new((2021, 11, 18), (12, 10, 00)).unwrap());
    }

    #[test]
    fn test_datetime_add_days() {
        let date = DateTime::new((2021, 11, 18), (12, 00, 00)).unwrap();
        let new = date.add(DateTime::days(3));
        assert_that!(new)
            .is_ok()
            .is_equal_to(&DateTime::new((2021, 11, 21), (12, 00, 00)).unwrap());
    }

    #[test]
    fn test_datetime_hhmm() {
        let date = DateTime::new((2021, 11, 18), (8, 5, 13)).unwrap();
        assert_that!(date.hhmm())
            .is_equal_to(&String::from("08:05"));
    }

    #[test]
    fn test_datetime_try_from_bad() {
        let date = DateTime::try_from("fred");
        assert_that!(&date).is_err();
    }
}