use std::time::{SystemTime, UNIX_EPOCH};

pub type Timestamp = u128;

pub fn time_millis() -> Timestamp {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("System time is before UNIX EPOCH.")
        .as_millis()
}

pub fn timestamp_relative(time_reference: Timestamp) -> String {
    let mut ts = (time_millis() - time_reference) as f32 / 1000.;
    let mut unit = "s";
    let mut rounding = 0;

    if ts > 60. {
        ts /= 60.;
        unit = "m";
        rounding = 1;

        if ts > 60. {
            ts /= 60.;
            unit = "h";
            rounding = 1;

            if ts > 24. {
                ts /= 24.;
                unit = "d";
                rounding = 2;
            }
        }
    }

    let mul = 10f32.powi(rounding);
    ts = (ts * mul).floor() / mul;

    format!("{}{}", ts, unit)
}
