summaryrefslogtreecommitdiffstats
path: root/src/timeman.rs
blob: 9d179999c60bfeb75096c9211cfd14272638b006 (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
use std::cell::RefCell;
use std::time::Duration;
use std::{fmt::Display, string};
use std::error::Error;

use crate::GameState;
use crate::window::ui::GameWindowUiState;

pub type Second = u64;

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

impl TimeMan
{
    pub fn new(time: Second)
    -> Self {
        Self {
            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)
    {
        match self.auto_tick {
            Some(advance) => { self.time += advance; },
            None => {}
        }
    }

    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 seconds > 0 { format!("{}s", seconds) } else { format!("") },
            if minutes > 0 { format!("{}m", minutes) } else { format!("") },
            if hours > 0 { format!("{}h", hours) } else { format!("") },
            if days > 0 { format!("{}d", days) } else { format!("") },
            if years > 0 { format!("{}y", years) } else { format!("") })
    }


} //impl TimeMan