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
use chrono::prelude::*;
use std::str::FromStr;

#[derive(Debug)]
#[allow(dead_code)]
pub struct TimeWarriorLine {
    tw_type: String,
    from: DateTime<Utc>,
    until: DateTime<Utc>,
    tags: Vec<String>,
    active: bool,
}

impl TimeWarriorLine {
    pub fn duration(&self) -> chrono::Duration {
        self.until - self.from
    }

    pub fn full_tag(&self) -> String {
        self.tags.join(" ")
    }

    //fix: use of deprecated struct `chrono::Date`: use `chrono::NaiveDate` instead
    pub fn get_day_naive(&self) -> NaiveDate {
        self.from.date_naive()
    }

    #[deprecated(since = "0.1.4", note = "please use `get_day_naive` instead")]
    pub fn get_day(&self) -> Date<Utc> {
        self.from.date()
    }
}

#[derive(Debug)]
pub enum TimeWarriorLineError {
    Generic(String),
    NoDate(),
}

impl FromStr for TimeWarriorLine {
    type Err = TimeWarriorLineError;

    // Parses a timewarrior line
    fn from_str(line: &str) -> Result<Self, Self::Err> {
        let mut parts = line.split_whitespace();

        let tw_type = match parts.next() {
            Some(a) => a.to_owned(),
            _ => {
                return Err(TimeWarriorLineError::Generic("Type parsing".to_owned()));
            }
        };

        let from = match parts.next() {
            Some(a) => {
                let f = match parse_date(a.to_owned()) {
                    Some(b) => b,
                    None => {
                        return Err(TimeWarriorLineError::NoDate());
                    }
                };
                f
            }
            _ => {
                return Err(TimeWarriorLineError::NoDate());
            }
        };

        let mut active = false;
        let until: DateTime<Utc> = match parts.next() {
            // no end date but tags
            Some("#") => {
                active = true;
                Utc::now()
            }
            // end date set
            Some("-") => {
                let utc = match parts.next() {
                    Some(u) => {
                        let stuff = parts.next();
                        match stuff {
                            Some("#") => (),
                            None => (),
                            _ => {
                                return Err(TimeWarriorLineError::Generic(
                                    format!("Unexpected {:?}", stuff).to_owned(),
                                ));
                            }
                        }
                        let f = match parse_date(u.to_owned()) {
                            Some(a) => a,
                            None => {
                                return Err(TimeWarriorLineError::Generic(
                                    format!("Unexpected {:?}", u).to_owned(),
                                ));
                            }
                        };
                        f
                    }
                    None => {
                        return Err(TimeWarriorLineError::Generic("nope".to_owned()));
                    }
                };
                utc
            }
            // no enddate and no tags
            None => {
                active = true;
                Utc::now()
            }
            // everything else is an error
            e => {
                return Err(TimeWarriorLineError::Generic(
                    format!("Unexpected {:?}", e).to_owned(),
                ));
            }
        };

        let str_nums: Vec<String> = parts.map(|n| n.to_string()).collect();

        let tagline = str_nums.join(" ");

        let mut multitag = false;
        let mut tag_string = "".to_owned();
        let mut tags = Vec::<String>::new();
        for one_char in tagline.chars() {
            match one_char {
                '"' => {
                    multitag = !multitag;
                }
                ' ' => {
                    if multitag {
                        tag_string.push(' ');
                    } else {
                        tags.push(tag_string);
                        tag_string = "".to_owned();
                    }
                }
                c => {
                    tag_string.push(c);
                }
            }
        }
        if tag_string != "" {
            tags.push(tag_string);
        }

        Ok(TimeWarriorLine {
            tw_type: tw_type,
            from: from,
            until: until,
            tags: tags,
            active: active,
        })
    }
}

fn parse_date(date_string: String) -> Option<DateTime<Utc>> {
    let from_part = format!("{} +0000", date_string);

    let date = match DateTime::parse_from_str(&from_part, "%Y%m%dT%H%M%SZ %z") {
        Ok(a) => Utc.from_local_datetime(&a.naive_local()).single(),
        Err(_) => None,
    };
    date
}

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

    #[test]
    fn garbage_in_err_out() {
        let result = TimeWarriorLine::from_str("afdf dafdf dsfads fdsaf");
        assert_eq!(
            result.is_err(),
            true,
            "line should not be parsed as ok result"
        );
    }

    #[test]
    fn only_z_is_valid_timezone_definition() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055CEST");
        assert_eq!(
            result.is_err(),
            true,
            "CEST line should not be parsed as ok result"
        );
    }

    #[test]
    fn only_broken_lines_1() {
        let result = TimeWarriorLine::from_str("inc");
        assert_eq!(
            result.is_err(),
            true,
            "line should not be parsed as ok result"
        );
    }

    #[test]
    fn only_broken_lines_2() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z - sdsadsad");
        assert_eq!(
            result.is_err(),
            true,
            "line should not be parsed as ok result"
        );
    }

    #[test]
    fn only_broken_lines_3() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z sadasds");
        assert_eq!(
            result.is_err(),
            true,
            "line should not be parsed as ok result"
        );
    }

    #[test]
    fn only_broken_lines_4() {
        let result =
            TimeWarriorLine::from_str("inc 20001011T133055Z - 20001011T183055Z dsafsadsads");
        assert_eq!(
            result.is_err(),
            true,
            "line should not be parsed as ok result"
        );
    }

    #[test]
    fn only_broken_lines_5() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z - ");
        assert_eq!(
            result.is_err(),
            true,
            "line should not be parsed as ok result"
        );
    }

    #[test]
    fn only_started_no_tags() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z");
        assert_eq!(result.is_ok(), true, "parsed line is not a ok result");

        let line = result.unwrap();

        assert_eq!(line.tw_type, "inc");
        assert_eq!(line.active, true);
        assert_eq!(line.tags, Vec::<String>::new());

        assert_eq!(line.full_tag(), "".to_owned());

        assert_eq!(line.from.format("%Y-%m-%d").to_string(), "2000-10-11");
        assert_eq!(line.from.format("%H:%M:%S").to_string(), "13:30:55");
    }

    #[test]
    fn only_started_one_tag() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z # Walala");
        assert_eq!(result.is_ok(), true, "parsed line is not a ok result");

        let line = result.unwrap();

        assert_eq!(line.tw_type, "inc");
        assert_eq!(line.active, true);
        assert_eq!(line.tags, vec!["Walala"]);

        assert_eq!(line.full_tag(), "Walala".to_owned());

        assert_eq!(line.from.format("%Y-%m-%d").to_string(), "2000-10-11");
        assert_eq!(line.from.format("%H:%M:%S").to_string(), "13:30:55");
    }

    #[test]
    fn only_start_and_enddate_no_tags() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z - 20001112T144054Z");
        assert_eq!(
            result.is_ok(),
            true,
            "parsed line is not a ok result {:?}",
            result
        );

        let line = result.unwrap();

        assert_eq!(line.tw_type, "inc");
        assert_eq!(line.active, false);
        assert_eq!(line.tags, Vec::<String>::new());

        assert_eq!(line.full_tag(), "".to_owned());

        assert_eq!(line.from.format("%Y-%m-%d").to_string(), "2000-10-11");
        assert_eq!(line.from.format("%H:%M:%S").to_string(), "13:30:55");

        assert_eq!(line.until.format("%Y-%m-%d").to_string(), "2000-11-12");
        assert_eq!(line.until.format("%H:%M:%S").to_string(), "14:40:54");
    }

    #[test]
    fn duration_is_correct() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z - 20001011T134055Z");
        assert_eq!(
            result.is_ok(),
            true,
            "parsed line is not a ok result {:?}",
            result
        );

        let line = result.unwrap();

        assert_eq!(line.duration(), chrono::Duration::minutes(10));
    }

    #[test]
    fn date_naive_is_correct() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z - 20001011T134055Z");
        assert_eq!(
            result.is_ok(),
            true,
            "parsed line is not a ok result {:?}",
            result
        );

        let line = result.unwrap();

        assert_eq!(
            line.get_day_naive(),
            chrono::NaiveDate::from_ymd_opt(2000, 10, 11).expect("Invalid date")
        );
    }

    #[test]
    fn date_is_correct() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z - 20001011T134055Z");
        assert_eq!(
            result.is_ok(),
            true,
            "parsed line is not a ok result {:?}",
            result
        );

        let line = result.unwrap();

        assert_eq!(line.get_day(), chrono::Utc.ymd(2000, 10, 11));
    }

    #[test]
    fn only_start_and_enddate_one_taga() {
        let result = TimeWarriorLine::from_str("inc 20001011T133055Z - 20001112T144054Z # Buvere");
        assert_eq!(
            result.is_ok(),
            true,
            "parsed line is not a ok result {:?}",
            result
        );

        let line = result.unwrap();

        assert_eq!(line.tw_type, "inc");
        assert_eq!(line.active, false);
        assert_eq!(line.tags, vec!["Buvere"]);

        assert_eq!(line.full_tag(), "Buvere".to_owned());

        assert_eq!(line.from.format("%Y-%m-%d").to_string(), "2000-10-11");
        assert_eq!(line.from.format("%H:%M:%S").to_string(), "13:30:55");

        assert_eq!(line.until.format("%Y-%m-%d").to_string(), "2000-11-12");
        assert_eq!(line.until.format("%H:%M:%S").to_string(), "14:40:54");
    }

    #[test]
    fn tags_with_spaces_are_recognized() {
        let result = TimeWarriorLine::from_str(
            "inc 20001011T133055Z - 20001112T144054Z # \"ABC CDE\" EFG HIJ",
        );
        assert_eq!(
            result.is_ok(),
            true,
            "parsed line is not a ok result {:?}",
            result
        );

        let line = result.unwrap();

        assert_eq!(line.tw_type, "inc");
        assert_eq!(line.active, false);
        assert_eq!(line.tags, vec!["ABC CDE", "EFG", "HIJ"]);

        // assert_eq!(line.full_tag(), "\"ABC CDE\" EFG HIJ".to_owned());

        assert_eq!(line.tags.len(), 3);
    }
}