use std::str::FromStr;

use serde::{Deserialize, Serialize};

/// Provides representation of what content visibility can be shown as.
#[derive(Copy, Clone, Debug, PartialEq, Hash, Eq, Default)]
pub enum Level {
    /// No restrictions on who can see this content.
    #[default]
    Public,

    /// Same as public, but hidden from associated feeds.
    Unlisted,

    /// Content can live in a feed but may require more information to view.
    Private,
}

impl FromStr for Level {
    type Err = crate::Error;

    fn from_str(v: &str) -> Result<Self, Self::Err> {
        match v.to_lowercase().as_str() {
            "private" => Ok(Level::Private),
            "unlisted" => Ok(Level::Unlisted),
            "public" => Ok(Level::Public),
            invalid => Err(Self::Err::InvalidVisibility(invalid.to_string())),
        }
    }
}

impl std::fmt::Display for Level {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Level::Public => "public",
            Level::Unlisted => "unlisted",
            Level::Private => "private",
        })
    }
}

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

impl<'de> Deserialize<'de> for Level {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        String::deserialize(deserializer)
            .and_then(|vs| Self::from_str(&vs).map_err(serde::de::Error::custom))
    }
}
