//! This mod wraps the event Ids
use super::addr::Error;
use bech32::FromBase32;
use secp256k1::XOnlyPublicKey;
use serde::{
    de::{self, Deserializer},
    ser::{self, Serializer},
    Deserialize,
};
use std::{
    fmt::{self, Display},
    ops::Deref,
    str::FromStr,
};

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

impl TryFrom<&str> for Id {
    type Error = Error;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let mut slice = [0u8; 32];
        if hex::decode_to_slice(value, &mut slice).is_ok() {
            return Ok(Id(slice));
        }
        let (hrp, bytes, _) = bech32::decode(&value)?;
        match hrp.to_lowercase().as_str() {
            "npub" | "nsec" | "note" => {}
            _ => return Err(Error::UnexpectedHrp),
        };

        let bytes: [u8; 32] = Vec::<u8>::from_base32(&bytes)?
            .try_into()
            .map_err(|_| bech32::Error::InvalidLength)?;

        Ok(Id(bytes))
    }
}

impl FromStr for Id {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.try_into()
    }
}

impl Id {
    /// Convert the Id to a vector of bytes
    pub fn into_bytes(self) -> Vec<u8> {
        self.0.to_vec()
    }
}

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 Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", 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 From<XOnlyPublicKey> for Id {
    fn from(public_key: XOnlyPublicKey) -> Self {
        Self(public_key.serialize())
    }
}

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())
    }
}
