use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct AssetUuid(uuid::Uuid);

impl AssetUuid {
    /// Creates a fresh, random `AssetUuid` (UUIDv4).
    pub fn random() -> Self {
        Self(uuid::Uuid::new_v4())
    }

    /// Deterministic id derived from `bytes` (UUIDv5). The same input
    /// always yields the same id, so content embedded in a scene keeps a
    /// stable key across saves instead of churning a fresh random id
    /// every time.
    pub fn from_content(bytes: &[u8]) -> Self {
        Self(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, bytes))
    }

    pub fn from_bytes(bytes: [u8; 16]) -> Self {
        Self(uuid::Uuid::from_bytes(bytes))
    }

    pub fn as_bytes(&self) -> &[u8; 16] {
        self.0.as_bytes()
    }

    pub fn to_uuid(&self) -> uuid::Uuid {
        self.0
    }

    pub fn from_uuid(uuid: uuid::Uuid) -> Self {
        Self(uuid)
    }
}

impl fmt::Debug for AssetUuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AssetUuid({})", self.0)
    }
}

impl fmt::Display for AssetUuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for AssetUuid {
    type Err = uuid::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let uuid = uuid::Uuid::parse_str(s)?;
        Ok(Self(uuid))
    }
}

impl From<uuid::Uuid> for AssetUuid {
    fn from(uuid: uuid::Uuid) -> Self {
        Self(uuid)
    }
}

impl From<AssetUuid> for uuid::Uuid {
    fn from(asset_uuid: AssetUuid) -> Self {
        asset_uuid.0
    }
}
