//! This mod wraps the event Ids
use serde::{
    de::{self, Deserializer},
    ser::{self, Serializer},
    Deserialize,
};
use std::ops::Deref;

/// Event Id
///
/// Event Id are raw 32 bytes and 64-character length hex encoded to JSON
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct Id(pub [u8; 32]);

impl AsRef<[u8]> for Id {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl Deref for Id {
    type Target = [u8; 32];
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl ToString for Id {
    fn to_string(&self) -> String {
        hex::encode(self.0)
    }
}

impl TryFrom<String> for Id {
    type Error = String;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Ok(Self(
            hex::decode(&value)
                .map_err(|e| e.to_string())?
                .try_into()
                .map_err(|_| "Invalid length for Id".to_string())?,
        ))
    }
}

impl<'de> Deserialize<'de> for Id {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = <String>::deserialize(deserializer)?;
        s.try_into().map_err(de::Error::custom)
    }
}

impl ser::Serialize for Id {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.to_string().as_str())
    }
}
