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
//! Structs defining different sets of arguments supplied on command line
//!
//! # Description
//!
//! - [`DateRangeArgs`] - representation of the start/end dates for a report.
//! - [`FilterArgs`] - representation of the start/end dates and project list for reports.
use std::iter::once;

use regex::Regex;

#[doc(inline)]
use crate::date::Date;
#[doc(inline)]
use crate::error::Error;
use crate::Day;
use crate::Result;

#[derive(Debug, PartialEq)]
pub struct PosIntArg(u32);

impl PosIntArg {
    /// Create a new [`PosIntArg`] from the supplied argument.
    pub fn new(num: u32) -> Result<Self> {
        (num != 0)
            .then(|| Self(num))
            .ok_or_else(|| Error::InvalidInt("0".to_owned()))
    }

    /// Parse the optional string into a [`PosIntArg`], use the value
    /// of `deflt` if the arg is `None`.
    pub fn parse(arg: &Option<String>, deflt: u32) -> Result<Self> {
        if deflt == 0 {
            return Err(Error::InvalidInt("0".to_owned()));
        }
        match arg.as_ref().map(|a| a.as_str()) {
            Some("0") => Err(Error::InvalidInt("0".to_owned())),
            Some(num) => Ok(Self(
                num.parse().map_err(|_| Error::InvalidInt(num.to_owned()))?
            )),
            None => Ok(Self(deflt)),
        }
    }

    /// Return the value of the arg
    pub fn val(&self) -> u32 { self.0 }
}

/// Trait specifying common functionality for the different filter arguments.
pub trait DayFilter {
    /// Return the start date as a [`String`]
    fn start(&self) -> String;
    /// Return the end date as a [`String`]
    fn end(&self) -> String;
    /// Return a [`Day`] object after appropriate filtering
    fn filter_day(&self, day: Day) -> Option<Day>;
}

// Return Some [`Day`] if the supplied day is not empty.
fn day_with_entries(day: Day) -> Option<Day> { (!day.is_empty()).then(|| day) }

/// Representation of the start/end date and project list arguments for reports.
#[derive(Debug)]
pub struct FilterArgs {
    start: Date,
    end: Date,
    projects: Option<Regex>,
}

// Return a [`Regex`] one of the supplied projects
fn regex_from_projs(projs: &[&str]) -> Result<Regex> {
    Regex::new(&projs.join("|")).map_err(|_| Error::BadProjectFilter)
}

impl FilterArgs {
    /// Create the [`FilterArgs`] from an array of strings.
    ///
    /// ## Errors
    ///
    /// - Return [`Error::BadProjectFilter`] if the supplied project Regexes are not valid
    /// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
    pub fn new(args: &[String]) -> Result<Self> {
        let mut project_list: Vec<&str> = Vec::new();
        let today = Date::parse("today")?;

        let mut arg_iter = args.iter();
        let start = match arg_iter.next() {
            None => return Ok(Self::from_date(today)),
            Some(arg) => (Date::parse(arg), arg),
        };
        let start = match start {
            (Ok(date), _) => date,
            (Err(_), arg) => {
                once(arg)
                    .chain(arg_iter)
                    .for_each(|arg| project_list.push(arg));
                return Ok(Self::from_date_and_proj(today, regex_from_projs(&project_list)?));
            }
        };
        let end = match arg_iter.next() {
            None => return Ok(Self::from_date(start)),
            Some(arg) => match Date::parse(arg) {
                Ok(date) => date.succ(),
                Err(_) => {
                    project_list.push(arg);
                    start.succ()
                }
            },
        };
        arg_iter.for_each(|arg| project_list.push(arg));
        let projects = (!project_list.is_empty())
            .then(|| regex_from_projs(&project_list))
            .transpose()?;

        (start < end)
            .then(|| Self { start, end, projects })
            .ok_or(Error::WrongDateOrder)
    }

    // Create a [`FilterArgs`] from a single supplied [`Date`].
    fn from_date(start: Date) -> Self {
        Self { start, end: start.succ(), projects: None }
    }

    // Create a [`FilterArgs`] from a single supplied [`Date`] and project [`Regex`].
    fn from_date_and_proj(start: Date, proj: Regex) -> Self {
        Self { start, end: start.succ(), projects: Some(proj) }
    }

    // Return an [`Option<&Regex>`] that determines how to match projects
    fn projects(&self) -> Option<&Regex> { self.projects.as_ref() }
}

impl DayFilter for FilterArgs {
    /// Return the start date as a [`String`]
    fn start(&self) -> String { self.start.to_string() }

    /// Return the end date as a [`String`]
    fn end(&self) -> String { self.end.to_string() }

    /// Return a [`Day`] object filtered as needed
    fn filter_day(&self, day: Day) -> Option<Day> {
        day_with_entries(match self.projects() {
            Some(re) => day.filtered_by_project(re),
            None => day,
        })
    }
}

/// Representation of the start and end date arguments for reports.
#[derive(Debug, PartialEq, Eq)]
pub struct DateRangeArgs {
    start: Date,
    end: Date
}

impl DateRangeArgs {
    /// Create the [`DateRangeArgs`] from an array of strings.
    ///
    /// ## Errors
    ///
    /// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
    pub fn new(args: &[String]) -> Result<Self> {
        let today = Date::parse("today")?;

        let mut arg_iter = args.iter();
        let start = match arg_iter.next() {
            None => return Ok(Self { start: today, end: today.succ() }),
            Some(arg) => Date::parse(arg)
                .map_err(|_| Error::UnexpectedArgument(arg.to_owned()))?,
        };
        let end = match arg_iter.next() {
            None => start.succ(),
            Some(arg) => Date::parse(arg)
                .map_err(|_| Error::UnexpectedArgument(arg.to_owned()))?
                .succ(),
        };
        match arg_iter.next() {
            Some(arg) => Err(Error::UnexpectedArgument(arg.to_owned())),
            None => {
                (start < end)
                    .then(|| Self { start, end })
                    .ok_or(Error::WrongDateOrder)
            },
        }
    }

    /// Return the start date as a [`String`]
    pub fn start(&self) -> String { self.start.to_string() }

    /// Return the end date as a [`String`]
    pub fn end(&self) -> String { self.end.to_string() }
}

impl DayFilter for DateRangeArgs {
    /// Return the start date as a [`String`]
    fn start(&self) -> String { self.start.to_string() }

    /// Return the end date as a [`String`]
    fn end(&self) -> String { self.end.to_string() }

    /// Return a [`Day`] object filtered as needed. If the day is empty,
    /// return None.
    fn filter_day(&self, day: Day) -> Option<Day> { day_with_entries(day) }
}

// Only used for testing, not particularly performant.
#[cfg(test)]
impl PartialEq for FilterArgs {
    fn eq(&self, other: &Self) -> bool {
        (self.start() == other.start())
            && (self.end() == other.end())
            && match (self.projects(), other.projects()) {
                (None, None) => true,
                (None, _) | (_, None) => false,
                (Some(lhs), Some(rhs)) => format!("{:?}", lhs) == format!("{:?}", rhs),
            }
    }
}

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

    // Test PosIntArg

    #[test]
    fn test_posint_no_arg() {
        assert_that!(PosIntArg::parse(&None, 5))
            .is_ok()
            .is_equal_to(&PosIntArg(5));
    }

    #[test]
    fn test_posint_int() {
        let arg: Option<String> = Some("2".to_string());
        assert_that!(PosIntArg::parse(&arg, 1))
            .is_ok()
            .is_equal_to(&PosIntArg(2));
    }

    #[test]
    fn test_posint_float() {
        let arg: Option<String> = Some("3.14".to_string());
        assert_that!(PosIntArg::parse(&arg, 1)).is_err();
    }

    #[test]
    fn test_posint_num_0() {
        let arg: Option<String> = Some("0".to_string());
        assert_that!(PosIntArg::parse(&arg, 1)).is_err();
    }

    #[test]
    fn test_posint_num_neg() {
        let arg: Option<String> = Some("-3".to_string());
        assert_that!(PosIntArg::parse(&arg, 5)).is_err();
    }

    // Test Filter

    #[test]
    fn test_filter_no_args() {
        let args = vec![];
        let expected = FilterArgs {
            start: Date::today(),
            end: Date::today().succ(),
            projects: None,
        };

        assert_that!(&FilterArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_filter_just_one_date() {
        let args = vec!["yesterday".to_string()];
        let expected = FilterArgs {
            start: Date::today().pred(),
            end: Date::today(),
            projects: None,
        };

        assert_that!(&FilterArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_filter_just_two_dates() {
        let args = vec!["2021-12-01".to_string(), "2021-12-07".to_string()];
        let expected = FilterArgs {
            start: Date::new(2021, 12, 1).unwrap(),
            end: Date::new(2021, 12, 8).unwrap(),
            projects: None,
        };

        assert_that!(&FilterArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_filter_just_project() {
        let args = vec!["project1".to_string()];
        let expected = FilterArgs {
            start: Date::today(),
            end: Date::today().succ(),
            projects: Some(Regex::new(r"project1").unwrap()),
        };

        assert_that!(&FilterArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_filter_just_multiple_projects() {
        let args = vec![
            "project1".to_string(),
            "cleanup".to_string(),
            "profit".to_string(),
        ];
        let expected = FilterArgs {
            start: Date::today(),
            end: Date::today().succ(),
            projects: Some(Regex::new(r"project1|cleanup|profit").unwrap()),
        };

        assert_that!(&FilterArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_filter_start_and_project() {
        let args = vec!["2021-12-01".to_string(), "project1".to_string()];
        let expected = FilterArgs {
            start: Date::new(2021, 12, 1).unwrap(),
            end: Date::new(2021, 12, 2).unwrap(),
            projects: Some(Regex::new(r"project1").unwrap()),
        };

        assert_that!(&FilterArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_filter_both_dates_and_project() {
        let args = vec![
            "2021-12-01".to_string(),
            "2021-12-07".to_string(),
            "project1".to_string(),
        ];
        let expected = FilterArgs {
            start: Date::new(2021, 12, 1).unwrap(),
            end: Date::new(2021, 12, 8).unwrap(),
            projects: Some(Regex::new(r"project1").unwrap()),
        };

        assert_that!(&FilterArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    // Test DateRange

    #[test]
    fn test_dates_no_args() {
        let args = vec![];
        let expected = DateRangeArgs {
            start: Date::today(),
            end: Date::today().succ(),
        };

        assert_that!(&DateRangeArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_dates_just_one_date() {
        let args = vec!["yesterday".to_string()];
        let expected = DateRangeArgs {
            start: Date::today().pred(),
            end: Date::today(),
        };

        assert_that!(&DateRangeArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }

    #[test]
    fn test_dates_both_dates() {
        let args = vec!["2021-12-01".to_string(), "2021-12-07".to_string()];
        let expected = DateRangeArgs {
            start: Date::new(2021, 12, 1).unwrap(),
            end: Date::new(2021, 12, 8).unwrap(),
        };

        assert_that!(&DateRangeArgs::new(&args))
            .is_ok()
            .is_equal_to(&expected);
    }
}