aboutsummaryrefslogtreecommitdiff
path: root/src/model/event.rs
blob: 2650c477e3fae7c79b88ce0b7f2455c9b4907c70 (plain)
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
use chrono::Timelike;
use chrono::{NaiveDate, NaiveTime};

// #[derive(Debug, Clone, sqlx::FromRow)]
#[derive(Debug, Clone)]
pub struct Event {
    pub date: NaiveDate,
    pub start: Option<NaiveTime>,
    pub end: Option<NaiveTime>,
    pub name: String,
}

impl Event {
    pub fn pprint(&self) -> String {
        let start = self.start.map(pprint_time).unwrap_or_default();
        let end = self
            .end
            .map(|t| format!("-{}", pprint_time(t)))
            .unwrap_or_default();
        let space = if self.start.is_some() || self.end.is_some() {
            " "
        } else {
            ""
        };
        format!("{}{}{}{}", start, end, space, self.name)
    }
}

fn pprint_time(t: NaiveTime) -> String {
    if t.minute() == 0 {
        format!("{}h", t.hour())
    } else {
        format!("{}h{}", t.hour(), t.minute())
    }
}

pub fn parse_time(t: &str) -> Option<NaiveTime> {
    match t.split('h').collect::<Vec<&str>>()[..] {
        [hours, minutes] => {
            if minutes.trim().is_empty() {
                NaiveTime::from_hms_opt(hours.parse().ok()?, 0, 0)
            } else {
                NaiveTime::from_hms_opt(hours.parse().ok()?, minutes.parse().ok()?, 0)
            }
        }
        _ => None,
    }
}