// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.chavatar.settings
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::CowStr;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::com_atproto::repo::strong_ref::StrongRef;
use crate::app_chavatar::settings;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct AvatarItem<'a> {
    #[serde(borrow)]
    pub id: CowStr<'a>,
    #[serde(borrow)]
    pub image: StrongRef<'a>,
}

/// Rotation configuration for a user.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Settings<'a> {
    #[serde(borrow)]
    pub avatars: Vec<settings::AvatarItem<'a>>,
    pub enabled: bool,
    #[serde(borrow)]
    pub interval: SettingsInterval<'a>,
    #[serde(borrow)]
    pub mode: SettingsMode<'a>,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SettingsInterval<'a> {
    _1h,
    _3h,
    _6h,
    _12h,
    _1d,
    _1w,
    _1mo,
    Other(CowStr<'a>),
}

impl<'a> SettingsInterval<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::_1h => "1h",
            Self::_3h => "3h",
            Self::_6h => "6h",
            Self::_12h => "12h",
            Self::_1d => "1d",
            Self::_1w => "1w",
            Self::_1mo => "1mo",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for SettingsInterval<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "1h" => Self::_1h,
            "3h" => Self::_3h,
            "6h" => Self::_6h,
            "12h" => Self::_12h,
            "1d" => Self::_1d,
            "1w" => Self::_1w,
            "1mo" => Self::_1mo,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for SettingsInterval<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "1h" => Self::_1h,
            "3h" => Self::_3h,
            "6h" => Self::_6h,
            "12h" => Self::_12h,
            "1d" => Self::_1d,
            "1w" => Self::_1w,
            "1mo" => Self::_1mo,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for SettingsInterval<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> serde::Serialize for SettingsInterval<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, 'a> serde::Deserialize<'de> for SettingsInterval<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for SettingsInterval<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for SettingsInterval<'_> {
    type Output = SettingsInterval<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            SettingsInterval::_1h => SettingsInterval::_1h,
            SettingsInterval::_3h => SettingsInterval::_3h,
            SettingsInterval::_6h => SettingsInterval::_6h,
            SettingsInterval::_12h => SettingsInterval::_12h,
            SettingsInterval::_1d => SettingsInterval::_1d,
            SettingsInterval::_1w => SettingsInterval::_1w,
            SettingsInterval::_1mo => SettingsInterval::_1mo,
            SettingsInterval::Other(v) => SettingsInterval::Other(v.into_static()),
        }
    }
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SettingsMode<'a> {
    Sequential,
    Random,
    Other(CowStr<'a>),
}

impl<'a> SettingsMode<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Sequential => "sequential",
            Self::Random => "random",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for SettingsMode<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "sequential" => Self::Sequential,
            "random" => Self::Random,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for SettingsMode<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "sequential" => Self::Sequential,
            "random" => Self::Random,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for SettingsMode<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> serde::Serialize for SettingsMode<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, 'a> serde::Deserialize<'de> for SettingsMode<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for SettingsMode<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for SettingsMode<'_> {
    type Output = SettingsMode<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            SettingsMode::Sequential => SettingsMode::Sequential,
            SettingsMode::Random => SettingsMode::Random,
            SettingsMode::Other(v) => SettingsMode::Other(v.into_static()),
        }
    }
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct SettingsGetRecordOutput<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Settings<'a>,
}

impl<'a> Settings<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, SettingsRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

impl<'a> LexiconSchema for AvatarItem<'a> {
    fn nsid() -> &'static str {
        "app.chavatar.settings"
    }
    fn def_name() -> &'static str {
        "avatarItem"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_chavatar_settings()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.id;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 13usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("id"),
                    max: 13usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

/// Marker type for deserializing records from this collection.

#[derive(Debug, Serialize, Deserialize)]
pub struct SettingsRecord;
impl XrpcResp for SettingsRecord {
    const NSID: &'static str = "app.chavatar.settings";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = SettingsGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<SettingsGetRecordOutput<'_>> for Settings<'_> {
    fn from(output: SettingsGetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

impl Collection for Settings<'_> {
    const NSID: &'static str = "app.chavatar.settings";
    type Record = SettingsRecord;
}

impl Collection for SettingsRecord {
    const NSID: &'static str = "app.chavatar.settings";
    type Record = SettingsRecord;
}

impl<'a> LexiconSchema for Settings<'a> {
    fn nsid() -> &'static str {
        "app.chavatar.settings"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_chavatar_settings()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.interval;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("interval"),
                    max: 10usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.mode;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("mode"),
                    max: 20usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod avatar_item_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Id;
        type Image;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Id = Unset;
        type Image = Unset;
    }
    ///State transition - sets the `id` field to Set
    pub struct SetId<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetId<S> {}
    impl<S: State> State for SetId<S> {
        type Id = Set<members::id>;
        type Image = S::Image;
    }
    ///State transition - sets the `image` field to Set
    pub struct SetImage<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetImage<S> {}
    impl<S: State> State for SetImage<S> {
        type Id = S::Id;
        type Image = Set<members::image>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `id` field
        pub struct id(());
        ///Marker type for the `image` field
        pub struct image(());
    }
}

/// Builder for constructing an instance of this type
pub struct AvatarItemBuilder<'a, S: avatar_item_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<StrongRef<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> AvatarItem<'a> {
    /// Create a new builder for this type
    pub fn new() -> AvatarItemBuilder<'a, avatar_item_state::Empty> {
        AvatarItemBuilder::new()
    }
}

impl<'a> AvatarItemBuilder<'a, avatar_item_state::Empty> {
    /// Create a new builder with all fields unset
    pub fn new() -> Self {
        AvatarItemBuilder {
            _state: PhantomData,
            _fields: (None, None),
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AvatarItemBuilder<'a, S>
where
    S: avatar_item_state::State,
    S::Id: avatar_item_state::IsUnset,
{
    /// Set the `id` field (required)
    pub fn id(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> AvatarItemBuilder<'a, avatar_item_state::SetId<S>> {
        self._fields.0 = Option::Some(value.into());
        AvatarItemBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AvatarItemBuilder<'a, S>
where
    S: avatar_item_state::State,
    S::Image: avatar_item_state::IsUnset,
{
    /// Set the `image` field (required)
    pub fn image(
        mut self,
        value: impl Into<StrongRef<'a>>,
    ) -> AvatarItemBuilder<'a, avatar_item_state::SetImage<S>> {
        self._fields.1 = Option::Some(value.into());
        AvatarItemBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AvatarItemBuilder<'a, S>
where
    S: avatar_item_state::State,
    S::Id: avatar_item_state::IsSet,
    S::Image: avatar_item_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> AvatarItem<'a> {
        AvatarItem {
            id: self._fields.0.unwrap(),
            image: self._fields.1.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> AvatarItem<'a> {
        AvatarItem {
            id: self._fields.0.unwrap(),
            image: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_chavatar_settings() -> LexiconDoc<'static> {
    #[allow(unused_imports)]
    use jacquard_common::{CowStr, deps::smol_str::SmolStr, types::blob::MimeType};
    use jacquard_lexicon::lexicon::*;
    use alloc::collections::BTreeMap;
    LexiconDoc {
        lexicon: Lexicon::Lexicon1,
        id: CowStr::new_static("app.chavatar.settings"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("avatarItem"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("id"), SmolStr::new_static("image")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("id"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(13usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("image"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("Rotation configuration for a user."),
                    ),
                    key: Some(CowStr::new_static("literal:self")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("enabled"),
                                SmolStr::new_static("interval"),
                                SmolStr::new_static("mode"), SmolStr::new_static("avatars")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("avatars"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#avatarItem"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("enabled"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("interval"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("mode"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(20usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod settings_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Mode;
        type Avatars;
        type Enabled;
        type Interval;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Mode = Unset;
        type Avatars = Unset;
        type Enabled = Unset;
        type Interval = Unset;
    }
    ///State transition - sets the `mode` field to Set
    pub struct SetMode<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetMode<S> {}
    impl<S: State> State for SetMode<S> {
        type Mode = Set<members::mode>;
        type Avatars = S::Avatars;
        type Enabled = S::Enabled;
        type Interval = S::Interval;
    }
    ///State transition - sets the `avatars` field to Set
    pub struct SetAvatars<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAvatars<S> {}
    impl<S: State> State for SetAvatars<S> {
        type Mode = S::Mode;
        type Avatars = Set<members::avatars>;
        type Enabled = S::Enabled;
        type Interval = S::Interval;
    }
    ///State transition - sets the `enabled` field to Set
    pub struct SetEnabled<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetEnabled<S> {}
    impl<S: State> State for SetEnabled<S> {
        type Mode = S::Mode;
        type Avatars = S::Avatars;
        type Enabled = Set<members::enabled>;
        type Interval = S::Interval;
    }
    ///State transition - sets the `interval` field to Set
    pub struct SetInterval<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetInterval<S> {}
    impl<S: State> State for SetInterval<S> {
        type Mode = S::Mode;
        type Avatars = S::Avatars;
        type Enabled = S::Enabled;
        type Interval = Set<members::interval>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `mode` field
        pub struct mode(());
        ///Marker type for the `avatars` field
        pub struct avatars(());
        ///Marker type for the `enabled` field
        pub struct enabled(());
        ///Marker type for the `interval` field
        pub struct interval(());
    }
}

/// Builder for constructing an instance of this type
pub struct SettingsBuilder<'a, S: settings_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<settings::AvatarItem<'a>>>,
        Option<bool>,
        Option<SettingsInterval<'a>>,
        Option<SettingsMode<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Settings<'a> {
    /// Create a new builder for this type
    pub fn new() -> SettingsBuilder<'a, settings_state::Empty> {
        SettingsBuilder::new()
    }
}

impl<'a> SettingsBuilder<'a, settings_state::Empty> {
    /// Create a new builder with all fields unset
    pub fn new() -> Self {
        SettingsBuilder {
            _state: PhantomData,
            _fields: (None, None, None, None),
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SettingsBuilder<'a, S>
where
    S: settings_state::State,
    S::Avatars: settings_state::IsUnset,
{
    /// Set the `avatars` field (required)
    pub fn avatars(
        mut self,
        value: impl Into<Vec<settings::AvatarItem<'a>>>,
    ) -> SettingsBuilder<'a, settings_state::SetAvatars<S>> {
        self._fields.0 = Option::Some(value.into());
        SettingsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SettingsBuilder<'a, S>
where
    S: settings_state::State,
    S::Enabled: settings_state::IsUnset,
{
    /// Set the `enabled` field (required)
    pub fn enabled(
        mut self,
        value: impl Into<bool>,
    ) -> SettingsBuilder<'a, settings_state::SetEnabled<S>> {
        self._fields.1 = Option::Some(value.into());
        SettingsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SettingsBuilder<'a, S>
where
    S: settings_state::State,
    S::Interval: settings_state::IsUnset,
{
    /// Set the `interval` field (required)
    pub fn interval(
        mut self,
        value: impl Into<SettingsInterval<'a>>,
    ) -> SettingsBuilder<'a, settings_state::SetInterval<S>> {
        self._fields.2 = Option::Some(value.into());
        SettingsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SettingsBuilder<'a, S>
where
    S: settings_state::State,
    S::Mode: settings_state::IsUnset,
{
    /// Set the `mode` field (required)
    pub fn mode(
        mut self,
        value: impl Into<SettingsMode<'a>>,
    ) -> SettingsBuilder<'a, settings_state::SetMode<S>> {
        self._fields.3 = Option::Some(value.into());
        SettingsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SettingsBuilder<'a, S>
where
    S: settings_state::State,
    S::Mode: settings_state::IsSet,
    S::Avatars: settings_state::IsSet,
    S::Enabled: settings_state::IsSet,
    S::Interval: settings_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Settings<'a> {
        Settings {
            avatars: self._fields.0.unwrap(),
            enabled: self._fields.1.unwrap(),
            interval: self._fields.2.unwrap(),
            mode: self._fields.3.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Settings<'a> {
        Settings {
            avatars: self._fields.0.unwrap(),
            enabled: self._fields.1.unwrap(),
            interval: self._fields.2.unwrap(),
            mode: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}