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
// task.rs
//
// define task type

//use chrono::prelude::*;
use chrono::naive::{NaiveDate, NaiveDateTime};
use chrono::{DateTime, Local, TimeZone};
use colored::*;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;

pub type Deadline = DateTime<Local>;

#[derive(thiserror::Error, Debug)]
pub enum DeadlineParseError {
    #[error("failed to parse the string as a datetime: {}", .string)]
    ParseError {
        string: String,
        #[source]
        source: chrono::format::ParseError,
    },
    #[error("failed to assign a timezone")]
    TimezoneError,
}

pub fn parse_deadline(s: &str) -> Result<Deadline, DeadlineParseError> {
    const DATE_FMT: &str = "%F";
    const DATETIME_FMT: &str = "%F %H:%M";

    let naive: NaiveDateTime = NaiveDate::parse_from_str(s, DATE_FMT)
        .map(|date| date.and_hms(0, 0, 0))
        .or(NaiveDateTime::parse_from_str(s, DATETIME_FMT))
        .map_err(|e| DeadlineParseError::ParseError {
            string: s.to_string(),
            source: e,
        })?;

    Local
        .from_local_datetime(&naive)
        .earliest()
        .ok_or_else(|| DeadlineParseError::TimezoneError)
}

#[allow(unused)]
pub fn now_deadline() -> Deadline {
    Local::now()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum Priority {
    Urgent,
    High,
    Normal,
    Low,
    Note,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct Task {
    pub description: String,
    pub priority: Option<Priority>,
    pub deadline: Option<Deadline>,
}

pub struct TaskBuilder {
    description: String,
    priority: Option<Priority>,
    deadline: Option<Deadline>,
}

impl TaskBuilder {
    pub fn new(description: String) -> TaskBuilder {
        TaskBuilder {
            description,
            priority: None,
            deadline: None,
        }
    }

    pub fn priority(mut self, priority: Priority) -> TaskBuilder {
        self.priority = Some(priority);
        self
    }

    pub fn deadline(mut self, deadline: Deadline) -> TaskBuilder {
        self.deadline = Some(deadline);
        self
    }

    pub fn build(self) -> Task {
        Task {
            description: self.description,
            priority: self.priority,
            deadline: self.deadline,
        }
    }
}

impl Task {
    /// Whether to choose this task or not
    ///
    /// # Examples
    ///
    /// ```
    /// use rustask::commands::task::*;
    /// let task = TaskBuilder::new("task".to_string()).priority(Priority::Urgent).build();
    /// assert_eq!(task.choose(), true);
    /// ```
    pub fn choose(&self) -> bool {
        use rand::{thread_rng, Rng};
        let mut rng = thread_rng();

        match self.priority.as_ref().unwrap_or(&Priority::Normal) {
            Priority::Urgent => true,
            Priority::High => true,
            Priority::Normal => {
                let prob = 1. / 3. + self.deadline_near();
                if prob < 1.0 {
                    rng.gen_bool(prob)
                } else {
                    true
                }
            }
            Priority::Low => {
                let prob = 1. / 5. + self.deadline_near();
                if prob < 1.0 {
                    rng.gen_bool(prob)
                } else {
                    true
                }
            }
            Priority::Note => {
                let prob = 1. / 8. + self.deadline_near();
                if prob < 1.0 {
                    rng.gen_bool(prob)
                } else {
                    true
                }
            }
        }
    }

    /// Whether there is a deadline near
    /// Yields a percentage, which can be read as an auxiliar priority level
    ///
    /// If a task is overdue or happening now, the percentage is 1.0
    /// If a task is more than a week in the future, the percentage is 0.0
    fn deadline_near(&self) -> f64 {
        if let Some(d) = self.deadline {
            let diff = d - now_deadline();
            if diff <= chrono::Duration::zero() {
                1.0
            } else if diff.num_weeks() > 0 {
                0.0
            } else {
                const MINUTES_IN_WEEK: f64 = (7 * 24 * 60) as f64;
                diff.num_minutes() as f64 / MINUTES_IN_WEEK
            }
        } else {
            0.0
        }
    }
}

impl fmt::Display for Task {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn display_diff(diff: chrono::Duration) -> String {
            let abs = if diff < chrono::Duration::zero() {
                -diff
            } else {
                diff
            };
            format!(
                "{} {}",
                if diff < chrono::Duration::zero() {
                    "overdue by"
                } else {
                    "in"
                },
                if abs.num_weeks() > 0 {
                    format!(
                        "{} week{}",
                        abs.num_weeks(),
                        if abs.num_weeks() == 1 { "" } else { "s" }
                    )
                } else if abs.num_days() > 0 {
                    format!(
                        "{} day{}",
                        abs.num_days(),
                        if abs.num_days() == 1 { "" } else { "s" }
                    )
                } else if abs.num_hours() > 0 {
                    format!(
                        "{} hour{}",
                        abs.num_hours(),
                        if abs.num_hours() == 1 { "" } else { "s" }
                    )
                } else if abs.num_minutes() > 15 {
                    format!(
                        "{} minute{}",
                        abs.num_minutes(),
                        if abs.num_minutes() == 1 { "" } else { "s" }
                    )
                } else {
                    "moments".to_string()
                }
            )
        }

        if let Some(deadline) = self.deadline {
            write!(
                f,
                "{} [{}]",
                match &self.priority {
                    Some(Priority::Urgent) => self.description.on_red().bold().bright_white(),
                    Some(Priority::High) => self.description.red(),
                    Some(Priority::Normal) => self.description.yellow(),
                    Some(Priority::Low) => self.description.green(),
                    Some(Priority::Note) => self.description.cyan(),
                    None => self.description.bold(),
                },
                display_diff(deadline - now_deadline())
            )
        } else {
            write!(
                f,
                "{}",
                match &self.priority {
                    Some(Priority::Urgent) => self.description.on_red().bold().bright_white(),
                    Some(Priority::High) => self.description.red(),
                    Some(Priority::Normal) => self.description.yellow(),
                    Some(Priority::Low) => self.description.green(),
                    Some(Priority::Note) => self.description.cyan(),
                    None => self.description.bold(),
                }
            )
        }
    }
}

pub struct ParsePriorityError {}

impl FromStr for Priority {
    type Err = ParsePriorityError;
    fn from_str(s: &str) -> Result<Self, ParsePriorityError> {
        match s.to_lowercase().as_str() {
            "urgent" => Ok(Priority::Urgent),
            "high" => Ok(Priority::High),
            "normal" => Ok(Priority::Normal),
            "low" => Ok(Priority::Low),
            "note" => Ok(Priority::Note),
            _ => Err(ParsePriorityError {}),
        }
    }
}

impl Ord for Task {
    fn cmp(&self, other: &Self) -> Ordering {
        let self_pri = self.priority.as_ref().unwrap_or(&Priority::Normal);
        let other_pri = other.priority.as_ref().unwrap_or(&Priority::Normal);
        if self_pri == other_pri {
            self.description.cmp(&other.description)
        } else {
            self_pri.cmp(&other_pri)
        }
    }
}

impl PartialOrd for Task {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn urgent_task_display() {
        let task = TaskBuilder::new("urgent task".to_string())
            .priority(Priority::Urgent)
            .build();
        assert_eq!(
            format!("Urgent Task: {}", task),
            format!(
                "Urgent Task: {}",
                "urgent task".on_red().bold().bright_white()
            ),
        );
    }

    #[test]
    fn high_task_display() {
        let task = TaskBuilder::new("high task".to_string())
            .priority(Priority::High)
            .build();
        assert_eq!(
            format!("High Task: {}", task),
            format!("High Task: {}", "high task".red()),
        );
    }

    #[test]
    fn normal_task_display() {
        let task = TaskBuilder::new("normal task".to_string())
            .priority(Priority::Normal)
            .build();
        assert_eq!(
            format!("Normal Task: {}", task),
            format!("Normal Task: {}", "normal task".yellow()),
        );
    }

    #[test]
    fn low_task_display() {
        let task = TaskBuilder::new("low task".to_string())
            .priority(Priority::Low)
            .build();
        assert_eq!(
            format!("Low Task: {}", task),
            format!("Low Task: {}", "low task".green()),
        );
    }

    #[test]
    fn note_display() {
        let task = TaskBuilder::new("note".to_string())
            .priority(Priority::Note)
            .build();
        assert_eq!(
            format!("Note: {}", task),
            format!("Note: {}", "note".cyan()),
        );
    }

    #[test]
    fn default_display() {
        let task = TaskBuilder::new("default".to_string()).build();
        assert_eq!(
            format!("Default: {}", task),
            format!("Default: {}", "default".bold()),
        );
    }

    #[test]
    fn urgent_filter() {
        let task = TaskBuilder::new("task".to_string())
            .priority(Priority::Urgent)
            .build();
        assert_eq!(task.choose(), true);
    }

    #[test]
    fn high_filter() {
        let task = TaskBuilder::new("task".to_string())
            .priority(Priority::High)
            .build();
        assert_eq!(task.choose(), true);
    }
}