use anyhow::Result;
use std::time::SystemTime;

pub fn seconds_since_unix_epoch() -> Result<u64> {
    seconds_since_unix_epoch_of(SystemTime::now())
}

pub fn seconds_since_unix_epoch_of(time: SystemTime) -> Result<u64> {
    Ok(time
        .duration_since(std::time::SystemTime::UNIX_EPOCH)?
        .as_secs())
}

/// Pretty print duration.
pub fn pp_duration(seconds: u64) -> String {
    let minutes = (seconds as f64 / 60.).round();
    let hours = (minutes / 60.).round();
    let days = (hours / 24.).round();

    if seconds < 60 {
        plural(seconds, "seconde")
    } else if minutes < 60. {
        plural(minutes as u64, "minute")
    } else if hours < 24. {
        plural(hours as u64, "heure")
    } else {
        plural(days as u64, "jour")
    }
}

fn plural(n: u64, str: &str) -> String {
    if n <= 1 {
        format!("{n} {str}")
    } else {
        format!("{n} {str}s")
    }
}