use crate::error::DatError;
use base64::engine::general_purpose;
use base64::Engine;
use std::time::SystemTime;
use crate::dat_key::Kid;
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 to_kid<T: Kid>(kid_text: &str) -> Result<T, DatError> {
kid_text.parse::<T>()
.map_err(|_| DatError::KeyError("invalid kid".to_string()))
}
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}")))
}