use base64;
use serde::{de::Error, Deserialize, Deserializer, Serializer, ser::SerializeSeq};

/// Deserialize base64 string to bytes.
pub fn base64_to_bytes<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<&str> = Deserialize::deserialize(deserializer)?;
    Ok(match value {
        Some(value) => base64::decode(value).map_err(D::Error::custom)?,
        None => vec![],
    })
}

/// Deserialize base64 string to bytes: Option<_>.
pub fn opt_base64_to_bytes<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<&str> = Deserialize::deserialize(deserializer)?;
    value
        .map(|value| base64::decode(value).map_err(D::Error::custom))
        .transpose()
}

/// Deserialize base64 string to bytes. Vec<_>.
pub fn vec_base64_to_bytes<'de, D>(deserializer: D) -> Result<Vec<Vec<u8>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Vec<&str> = Deserialize::deserialize(deserializer)?;
    value
        .into_iter()
        .map(|value| base64::decode(value).map_err(D::Error::custom))
        .collect()
}

/// Serialize bytes to base64 string.
pub fn bytes_to_base64<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(&base64::encode(bytes))
}

/// Serialize bytes to base64 string: Option<_>.
pub fn opt_bytes_to_base64<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if bytes.is_empty() {
        serializer.serialize_none()
    } else {
        serializer.serialize_some(&base64::encode(bytes))
    }
}

/// Serialize bytes to base64 string: Vec<_>.
pub fn vec_bytes_to_base64<S>(vec_bytes: &[Vec<u8>], serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut seq = serializer.serialize_seq(Some(vec_bytes.len()))?;
    for bytes in vec_bytes {
        seq.serialize_element(&base64::encode(bytes))?;
    }
    seq.end()
}
