use base64::{prelude::BASE64_STANDARD, Engine};
use chrono::{DateTime, Duration, Local, Utc};
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};

pub struct HttpDate(DateTime<Utc>);

impl fmt::Display for HttpDate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} GMT", self.0.format("%a, %d %b %Y %H:%M:%S"))
    }
}

/// 获取当前时间的GMT格式字符串
/// 
/// 输出格式形如："Fri, 22 Aug 2025 08:20:48 GMT"
pub fn now_str_gmt() -> String {
    let now = Utc::now();
    let http_date = HttpDate(now);
    http_date.to_string()
}

pub fn base64_md5_str(data: &Vec<u8>) -> String {
    let data_md5 = md5::compute(data).to_vec();
    BASE64_STANDARD.encode(data_md5)
}

pub fn timestamp(time: DateTime<Local>, seconds: i64) -> u64 {
    let diff = Duration::seconds(seconds);
    let time = time + diff;
    let system_time: SystemTime = time.into();
    let duration = system_time.duration_since(UNIX_EPOCH).unwrap();
    let timestamp = duration.as_secs();
    timestamp
}

/// 根据文件后缀获取文件类型
pub fn get_mime_type_from_extension(path: &str) -> Option<String> {
    let guess = mime_guess::from_path(path);
    guess.first().map(|mime| mime.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mime_type() {
        let suff = get_mime_type_from_extension("tmp/xxx.png").unwrap();
        println!("suf = {}", suff);
    }

}