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

#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AssetUuid([u8; 16]);

impl AssetUuid {
    pub const NIL: Self = Self([0u8; 16]);

    pub fn new() -> Self {
        Self(uuid::Uuid::new_v4().into_bytes())
    }

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

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

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

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

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

impl Default for AssetUuid {
    fn default() -> Self {
        Self::NIL
    }
}

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

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

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::from_uuid(uuid))
    }
}

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

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