use crate::error::DatError;
use crate::util::encode_base64_url_no_pad;
use std::fmt::Display;

pub struct DatPayload {
    pub expire: u64,
    pub plain_bytes: Vec<u8>,
    pub secure_bytes: Vec<u8>,
}

pub struct DatStringPayload {
    pub expire: u64,
    pub plain: String,
    pub secure: String,
}

impl DatPayload {
    pub fn to_string_payload(self) -> Result<DatStringPayload, DatError> {
        Ok(DatStringPayload {
            expire: self.expire,
            plain: String::from_utf8(self.plain_bytes).map_err(|_| DatError::Utf8EncodeError)?,
            secure: String::from_utf8(self.secure_bytes).map_err(|_| DatError::Utf8EncodeError)?,
        })
    }
}

impl Display for DatPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.expire, encode_base64_url_no_pad(&*self.plain_bytes), encode_base64_url_no_pad(&*self.secure_bytes))
    }
}

impl Display for DatStringPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}\n{}\n{}", self.expire, self.plain, self.secure)
    }
}
