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
use chrono::{Duration, Local, NaiveDateTime};
use std::fmt;
use std::str::{Chars, FromStr};
use thiserror::Error;

use crate::conf;

#[derive(Debug, Clone)]
pub struct Activity {
    pub start: NaiveDateTime,
    pub end: Option<NaiveDateTime>,

    pub project: String,
    pub description: String,
}

#[derive(Error, Debug)]
pub enum ActivityError {
    #[error("could not parse date or time of activity")]
    DateTimeParseError,
    #[error("could not parse activity")]
    GeneralParseError,
}

impl Activity {
    #[must_use]
    pub fn start(project: String, description: String, time: Option<NaiveDateTime>) -> Self {
        Self {
            start: time.unwrap_or_else(|| Local::now().naive_local()),
            end: None,
            project,
            description,
        }
    }

    pub fn stop(&mut self, time: Option<NaiveDateTime>) {
        self.end = time.or_else(|| Some(Local::now().naive_local()));
    }

    #[must_use]
    pub fn is_stopped(&self) -> bool {
        self.end.is_some()
    }

    #[must_use]
    pub fn get_duration(&self) -> Duration {
        if let Some(end) = self.end {
            end.signed_duration_since(self.start)
        } else {
            Local::now().naive_local().signed_duration_since(self.start)
        }
    }
}

impl fmt::Display for Activity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let escaped_project_name = escape_special_chars(self.project.as_str());
        let escaped_description = escape_special_chars(&self.description);

        match self.end {
            None => writeln!(
                f,
                "{} | {} | {}",
                self.start.format(conf::FORMAT_DATETIME),
                escaped_project_name,
                escaped_description
            ),
            Some(end) => writeln!(
                f,
                "{} - {} | {} | {}",
                self.start.format(conf::FORMAT_DATETIME),
                end.format(conf::FORMAT_DATETIME),
                escaped_project_name,
                escaped_description
            ),
        }
    }
}

// escapes the pipe character, so we can use it to separate the distinct parts of a activity
fn escape_special_chars(s: &str) -> String {
    s.replace('\\', "\\\\").replace('|', "\\|")
}

impl FromStr for Activity {
    type Err = ActivityError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<String> = split_with_escaped_delimiter(s).collect();

        if parts.len() < 2 {
            return Err(ActivityError::GeneralParseError);
        }

        let time_parts: Vec<&str> = parts[0].split(" - ").collect();

        let starttime = parse_timepart(time_parts[0])?;
        let endtime: Option<NaiveDateTime> = if time_parts.len() > 1 {
            Some(parse_timepart(time_parts[1])?)
        } else {
            None
        };

        let project = parts[1].trim();
        let description = if parts.len() > 2 { parts[2].trim() } else { "" };

        let activity = Self {
            start: starttime,
            end: endtime,
            project: project.to_string(),
            description: description.to_string(),
        };

        Ok(activity)
    }
}

fn parse_timepart(time_part: &str) -> Result<NaiveDateTime, ActivityError> {
    NaiveDateTime::parse_from_str(time_part.trim(), conf::FORMAT_DATETIME)
        .map_err(|_| ActivityError::DateTimeParseError)
}

/**
 * an iterator for splitting strings at the pipe character "|"
 *
 * this iterator splits strings at the pipe character. It ignores all pipe characters
 * that are properly escaped by backslash.
 */
struct StringSplitter<'a> {
    chars: Chars<'a>,
}

impl Iterator for StringSplitter<'_> {
    type Item = String;

    fn next(&mut self) -> Option<String> {
        let mut next_char = self.chars.next();

        next_char?;

        let mut escaped = false;
        let mut collector = String::new();

        loop {
            match next_char {
                Some('\\') if !escaped => {
                    escaped = true;
                }
                Some('|') if !escaped => {
                    return Some(collector);
                }
                Some(c) => {
                    escaped = false;
                    collector.push(c);
                }
                None => return Some(collector),
            }

            next_char = self.chars.next();
        }
    }
}

fn split_with_escaped_delimiter(s: &str) -> StringSplitter {
    StringSplitter { chars: s.chars() }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Datelike, Timelike};
    use std::option::Option::None;

    #[test]
    fn start() {
        let t = Activity::start(
            "test project".to_string(),
            "test description".to_string(),
            None,
        );
        assert_eq!(t.description, "test description".to_string());
        assert_eq!(t.project, "test project".to_string());
        assert_eq!(t.end, None);
    }

    #[test]
    fn stop() {
        let mut t = Activity::start(
            "test project".to_string(),
            "test description".to_string(),
            None,
        );
        t.stop(None);
        assert_ne!(t.end, None);
    }

    #[test]
    fn display() {
        let mut t = Activity::start(
            "test project| 1".to_string(),
            "test\\description".to_string(),
            None,
        );
        t.start = NaiveDateTime::parse_from_str("2021-02-16 16:14", conf::FORMAT_DATETIME).unwrap();
        assert_eq!(
            format!("{t}"),
            "2021-02-16 16:14 | test project\\| 1 | test\\\\description\n"
        );
        t.end =
            Some(NaiveDateTime::parse_from_str("2021-02-16 18:23", conf::FORMAT_DATETIME).unwrap());
        assert_eq!(
            format!("{t}"),
            "2021-02-16 16:14 - 2021-02-16 18:23 | test project\\| 1 | test\\\\description\n"
        );
    }

    #[test]
    fn from_str_running_activity() {
        let t = Activity::from_str("2021-02-16 16:14 | test project | test description").unwrap();

        assert_eq!(t.start.date().year(), 2021);
        assert_eq!(t.start.date().month(), 2);
        assert_eq!(t.start.date().day(), 16);

        assert_eq!(t.start.time().hour(), 16);
        assert_eq!(t.start.time().minute(), 14);

        assert_eq!(t.description, "test description".to_string());
        assert_eq!(t.project, "test project".to_string());
        assert_eq!(t.end, None);
    }

    #[test]
    fn from_str_running_activity_no_description() {
        let t = Activity::from_str("2021-02-16 16:14 | test project").unwrap();

        assert_eq!(t.start.date().year(), 2021);
        assert_eq!(t.start.date().month(), 2);
        assert_eq!(t.start.date().day(), 16);

        assert_eq!(t.start.time().hour(), 16);
        assert_eq!(t.start.time().minute(), 14);

        assert_eq!(t.description, String::new());
        assert_eq!(t.project, "test project".to_string());
        assert_eq!(t.end, None);
    }

    #[test]
    fn from_str_stopped_activity() {
        let t = Activity::from_str(
            "2021-02-16 16:14 - 2021-02-16 18:23 | test project | test description",
        )
        .unwrap();

        assert_ne!(t.end, None);

        let end = t.end.unwrap();

        assert_eq!(end.date().year(), 2021);
        assert_eq!(end.date().month(), 2);
        assert_eq!(end.date().day(), 16);

        assert_eq!(end.time().hour(), 18);
        assert_eq!(end.time().minute(), 23);
    }

    #[test]
    fn from_str_escaped_chars() {
        let t = Activity::from_str(
            "2021-02-16 16:14 - 2021-02-16 18:23 | test project\\| 1 | test\\\\description",
        )
        .unwrap();

        assert_eq!(t.project, "test project| 1");
        assert_eq!(t.description, "test\\description");
    }

    #[test]
    fn string_roundtrip() {
        let mut t = Activity::start(
            "ex\\ample\\\\pro|ject".to_string(),
            "e\\\\xam|||ple tas\t\t\nk".to_string(),
            None,
        );
        t.stop(None);
        let t2 = Activity::from_str(format!("{t}").as_str()).unwrap();

        assert_eq!(
            t.start.with_second(0).unwrap().with_nanosecond(0).unwrap(),
            t2.start
        );
        assert_eq!(
            t.end
                .unwrap()
                .with_second(0)
                .unwrap()
                .with_nanosecond(0)
                .unwrap(),
            t2.end.unwrap()
        );

        assert_eq!(t.project, t2.project);
        assert_eq!(t.description, t2.description);
    }

    #[test]
    fn from_str_errors() {
        let t = Activity::from_str("2021 test project");
        assert!(matches!(t, Err(ActivityError::GeneralParseError)));

        let t = Activity::from_str("asb - 2021- | project");
        assert!(matches!(t, Err(ActivityError::DateTimeParseError)));
    }
}