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
use super::errors;
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::ops::Add;
use std::path::PathBuf;

type DT = DateTime<Utc>;

#[derive(Debug, Serialize, Deserialize)]
pub struct Project {
    name: String,
    initial_date: DT,
    sessions: Vec<Session>,
}

impl Project {
    /// Get a reference to the project's name.
    pub fn name(&self) -> &String {
        &self.name
    }

    /// Get a reference to the project's initial date.
    pub fn initial_date(&self) -> &DT {
        &self.initial_date
    }

    /// Get a reference to the project's sessions.
    pub fn sessions(&self) -> &Vec<Session> {
        &self.sessions
    }

    // Only pub(super), because pub(in ...) can only contain ancestors and not siblings :(
    pub(super) fn create(name: &str) -> errors::CtResult<Project> {
        //// check if project already exists -> either fail or return existing project
        // This shouldn't be done, that's what ProjectFrame is for
        if super::has(name)? {
            Err(errors::CtError::Own("Project already exists"))
        } else {
            Ok(Project {
                name: name.to_owned(),
                // Maybe make time provider configurable so it can be mocked for easier testing
                initial_date: Utc::now(),
                sessions: vec![],
            })
        }
    }

    pub(super) fn from_json(json: &str) -> errors::CtResult<Project> {
        serde_json::from_str(json).map_err(|e| e.into())
    }

    pub fn json(&self, pretty: bool) -> errors::CtResult<String> {
        if pretty {
            serde_json::to_string_pretty(self).map_err(|e| e.into())
        } else {
            serde_json::to_string(self).map_err(|e| e.into())
        }
    }

    pub(super) fn start(&mut self) {
        // First check if a session is running
        // Should actually always be the last one
        for s in self.sessions.iter() {
            if s.end.is_none() {
                // We have an open session
                return;
            }
        }
        // We have no open session, so we can push one
        self.sessions.push(Session::new());
    }

    pub(super) fn stop(&mut self) {
        let open: Vec<&mut Session> = self.sessions.iter_mut().filter(|s| s.is_open()).collect();
        // For now assert that theres only one open session (or none)
        assert!(open.len() < 2);

        // We have asserted that there's less than one session,
        // so we can just use a loop to close them all
        for s in open {
            s.close();
        }
    }

    pub fn is_open(&self) -> bool {
        self.sessions.iter().fold(false, |acc, x| acc | x.is_open())
    }

    pub fn duration(&self) -> Duration {
        self.sessions
            .iter()
            .map(|s| s.timespan())
            .fold(Duration::zero(), Duration::add)
    }

    pub fn session_count(&self) -> usize {
        self.sessions.len()
    }

    pub fn load(path: &PathBuf) -> errors::CtResult<Project> {
        assert!(path.exists());
        assert!(path.is_file());
        // Project already exists: Try to load it and return a new frame
        let json = std::fs::read_to_string(&path)?;
        Project::from_json(json.as_str())
    }

    pub fn load_from_name(name: &str) -> errors::CtResult<Project> {
        Self::load(&super::project_path(name)?)
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub struct Session {
    start: DT,
    end: Option<DT>,
}

impl Session {
    fn new() -> Session {
        Session {
            start: Utc::now(),
            end: None,
        }
    }

    pub fn is_open(&self) -> bool {
        self.end.is_none()
    }

    fn close(&mut self) {
        assert!(self.end == None);
        self.end = Some(Utc::now());
    }

    pub fn timespan(&self) -> Duration {
        let start = self.start;
        // If this session is running, its current spanning time runs up until Utc::now()
        let end = self.end.unwrap_or_else(Utc::now);
        end.signed_duration_since(start)
    }

    pub fn start_time(&self) -> &DT {
        &self.start
    }

    pub fn end_time(&self) -> Option<&DT> {
        if let Some(t) = &self.end {
            Some(t)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use chrono::{Duration, Utc};
    use std::ops::Add;

    use super::{Project, Session, DT};

    struct TimeProvider {
        /// The current internal state
        state: i32,
        /// The number of timestamps to give
        num: i32,
        /// The base timestamp
        base_time: DT,
        timestep: Duration,
    }

    impl TimeProvider {
        fn new(timestep: Duration) -> TimeProvider {
            Self::lim(-1, timestep)
        }

        fn lim(num: i32, timestep: Duration) -> TimeProvider {
            TimeProvider {
                state: 0,
                num,
                base_time: Utc::now(),
                timestep,
            }
        }
    }

    impl Iterator for TimeProvider {
        type Item = DT;

        fn next(&mut self) -> Option<Self::Item> {
            if self.num <= 0 || self.state <= self.num {
                self.state += 1;
                self.base_time = self.base_time.add(self.timestep);
                Some(self.base_time)
            } else {
                None
            }
        }
    }

    impl Project {
        fn create_test(session_count: usize, timestep: Duration) -> Project {
            let mut t = TimeProvider::new(timestep);
            let initial_date = t.next().unwrap();
            let mut sessions = Vec::with_capacity(session_count);
            for _ in 1..=session_count {
                sessions.push(Session::mock(&mut t));
            }
            Project {
                name: "TEST".to_owned(),
                initial_date,
                sessions,
            }
        }
    }

    impl Session {
        fn mock(t: &mut TimeProvider) -> Session {
            if let Some(time) = t.next() {
                Session {
                    start: time,
                    end: t.next(),
                }
            } else {
                Session {
                    start: Utc::now(),
                    end: Some(Utc::now()),
                }
            }
        }
    }

    #[test]
    fn duration() {
        let timestep = Duration::seconds(5);
        let session_count = 10;
        let p = Project::create_test(session_count, timestep);
        assert_eq!(
            Duration::seconds(timestep.num_seconds() * session_count as i64),
            p.duration()
        );
    }

    #[test]
    fn multiple_start() {
        let mut p = Project::create("TEST").unwrap();

        // Multiple starts shouldn't lead to multiple sessions
        p.start();
        p.start();
        p.start();

        println!("Project has {} sessions", p.sessions.len());
        assert_eq!(p.sessions.len(), 1);

        // ...therefore one stop should suffice
        p.stop();

        let has_open_sessions = p.sessions.iter().fold(false, |acc, x| acc | x.is_open());
        println!("Project has open sessions? {}", has_open_sessions);
        assert!(!has_open_sessions);

        println!("Test finished successfully");
    }

    #[test]
    fn session_timespan() {
        let dur = Duration::seconds(5);
        let mut t = TimeProvider::new(dur);
        let s = Session::mock(&mut t);
        assert_eq!(dur, s.timespan());
    }
}