summaryrefslogtreecommitdiffstats
path: root/src/timeman.rs
blob: 62296d77cc221a5623da64dfb8f970820d6fe2a6 (plain) (blame)
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
pub type Second = i64;

pub const MINUTE: Second = 60;
pub const HOUR: Second = MINUTE * 60;
pub const DAY: Second = HOUR * 24;
pub const YEAR: Second = DAY * 365;

pub struct TimeMan
{
    time: Second,
    last_time: Second,
    pub auto_tick: Option<Second>
}

impl TimeMan
{
    pub fn new(time: Second)
    -> Self {
        Self {
            time,
            last_time: time,
            auto_tick: None
        }
    }

    pub fn seconds(&self)
    -> Second {
        self.time
    }

    pub fn advance(
        &mut self,
        by: Second)
    {
        self.time += by;
    }

    pub fn update(
        &mut self)
    -> Second
    {
        match self.auto_tick {
            Some(advance) => { self.time += advance; },
            None => {}
        }

        let last_time = self.last_time;
        self.last_time = self.time;
        last_time
    }

    pub fn format_duration(time: Second) -> String
    {
        let seconds = time % 60;
        let minutes = (time / 60) % 60;
        let hours = (time / (60 * 60)) % 24;
        let days = (time / (60 * 60 * 24)) % 365;
        let years = time / (60 * 60 * 24 * 365);
        
        if time == 0 {
            return "0s".to_string();
        }

        format!("{}{}{}{}{}",
            if years > 0 { format!("{}y", years) } else { format!("") },
            if days > 0 { format!("{}d", days) } else { format!("") },
            if hours > 0 { format!("{}h", hours) } else { format!("") },
            if minutes > 0 { format!("{}m", minutes) } else { format!("") },
            if seconds > 0 { format!("{}s", seconds) } else { format!("") })
    }


} //impl TimeMan