use std::time::SystemTime;
use base64::Engine;
use base64::engine::general_purpose;
use time::OffsetDateTime;
use crate::error::DatError;

pub const ENGINE_URL_SAFE_NO_PAD: &general_purpose::GeneralPurpose = &general_purpose::URL_SAFE_NO_PAD;

pub fn encode_base64_url_no_pad<T: AsRef<[u8]>>(b: T) -> String {
    ENGINE_URL_SAFE_NO_PAD.encode(b)
}

pub fn decode_base64_url_no_pad<T: AsRef<[u8]>>(b64: T) -> Result<Vec<u8>, DatError> {
    ENGINE_URL_SAFE_NO_PAD.decode(&b64)
        .map_err(|e| DatError::IoError(format!("base64 decode error: {e}")))
}

pub fn now_unix_timestamp() -> Result<i64, DatError> {
    SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
        .map(|e| e.as_secs() as i64)
        .map_err(|e| DatError::IoError(format!("unixtime error{e}")))
}

pub fn to_offset_date_time(time: i64) -> Result<OffsetDateTime, DatError> {
    OffsetDateTime::from_unix_timestamp(time)
        .map_err(|e| DatError::DatError(format!("TimeParseError: {}", e)))
}
