// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.protoimsg.chat.community
//
// 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, BosStr, DefaultStr, FromStaticStr};

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::deps::smol_str::SmolStr;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{Did, AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
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::app_protoimsg::chat::community;
/// A named group of community members.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CommunityGroup<S: BosStr = DefaultStr> {
    ///Whether this is an inner circle group for presence visibility.  Defaults to `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_community_group_is_inner_circle")]
    pub is_inner_circle: Option<bool>,
    ///DIDs of group members.
    pub members: Vec<community::CommunityMember<S>>,
    ///Group label.
    pub name: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A member in a community group.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CommunityMember<S: BosStr = DefaultStr> {
    ///When this member was added.
    pub added_at: Datetime,
    ///The member's DID.
    pub did: Did<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// The user's community list. Portable across any app implementing the Lexicon.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.protoimsg.chat.community",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Community<S: BosStr = DefaultStr> {
    ///Named groups of community members, like AIM's buddy list categories.
    pub groups: Vec<community::CommunityGroup<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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 CommunityGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Community<S>,
}

impl<S: BosStr> Community<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, CommunityRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

impl<S: BosStr> LexiconSchema for CommunityGroup<S> {
    fn nsid() -> &'static str {
        "app.protoimsg.chat.community"
    }
    fn def_name() -> &'static str {
        "communityGroup"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_protoimsg_chat_community()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.members;
            #[allow(unused_comparisons)]
            if value.len() > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("members"),
                    max: 500usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for CommunityMember<S> {
    fn nsid() -> &'static str {
        "app.protoimsg.chat.community"
    }
    fn def_name() -> &'static str {
        "communityMember"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_protoimsg_chat_community()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct CommunityRecord;
impl XrpcResp for CommunityRecord {
    const NSID: &'static str = "app.protoimsg.chat.community";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = CommunityGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<CommunityGetRecordOutput<S>> for Community<S> {
    fn from(output: CommunityGetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Community<S> {
    const NSID: &'static str = "app.protoimsg.chat.community";
    type Record = CommunityRecord;
}

impl Collection for CommunityRecord {
    const NSID: &'static str = "app.protoimsg.chat.community";
    type Record = CommunityRecord;
}

impl<S: BosStr> LexiconSchema for Community<S> {
    fn nsid() -> &'static str {
        "app.protoimsg.chat.community"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_protoimsg_chat_community()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.groups;
            #[allow(unused_comparisons)]
            if value.len() > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("groups"),
                    max: 50usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

fn _default_community_group_is_inner_circle() -> Option<bool> {
    Some(false)
}

pub mod community_group_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 Members;
        type Name;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Members = Unset;
        type Name = Unset;
    }
    ///State transition - sets the `members` field to Set
    pub struct SetMembers<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetMembers<St> {}
    impl<St: State> State for SetMembers<St> {
        type Members = Set<members::members>;
        type Name = St::Name;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type Members = St::Members;
        type Name = Set<members::name>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `members` field
        pub struct members(());
        ///Marker type for the `name` field
        pub struct name(());
    }
}

/// Builder for constructing an instance of this type.
pub struct CommunityGroupBuilder<
    St: community_group_state::State,
    S: BosStr = DefaultStr,
> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<bool>, Option<Vec<community::CommunityMember<S>>>, Option<S>),
    _type: PhantomData<fn() -> S>,
}

impl CommunityGroup<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> CommunityGroupBuilder<community_group_state::Empty, DefaultStr> {
        CommunityGroupBuilder::new()
    }
}

impl<S: BosStr> CommunityGroup<S> {
    /// Create a new builder for this type
    pub fn builder() -> CommunityGroupBuilder<community_group_state::Empty, S> {
        CommunityGroupBuilder::builder()
    }
}

impl CommunityGroupBuilder<community_group_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        CommunityGroupBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> CommunityGroupBuilder<community_group_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        CommunityGroupBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<St: community_group_state::State, S: BosStr> CommunityGroupBuilder<St, S> {
    /// Set the `isInnerCircle` field (optional)
    pub fn is_inner_circle(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `isInnerCircle` field to an Option value (optional)
    pub fn maybe_is_inner_circle(mut self, value: Option<bool>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> CommunityGroupBuilder<St, S>
where
    St: community_group_state::State,
    St::Members: community_group_state::IsUnset,
{
    /// Set the `members` field (required)
    pub fn members(
        mut self,
        value: impl Into<Vec<community::CommunityMember<S>>>,
    ) -> CommunityGroupBuilder<community_group_state::SetMembers<St>, S> {
        self._fields.1 = Option::Some(value.into());
        CommunityGroupBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommunityGroupBuilder<St, S>
where
    St: community_group_state::State,
    St::Name: community_group_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<S>,
    ) -> CommunityGroupBuilder<community_group_state::SetName<St>, S> {
        self._fields.2 = Option::Some(value.into());
        CommunityGroupBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommunityGroupBuilder<St, S>
where
    St: community_group_state::State,
    St::Members: community_group_state::IsSet,
    St::Name: community_group_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> CommunityGroup<S> {
        CommunityGroup {
            is_inner_circle: self._fields.0.or_else(|| Some(false)),
            members: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> CommunityGroup<S> {
        CommunityGroup {
            is_inner_circle: self._fields.0.or_else(|| Some(false)),
            members: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_protoimsg_chat_community() -> 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.protoimsg.chat.community"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("communityGroup"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("A named group of community members."),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("name"), SmolStr::new_static("members")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("isInnerCircle"),
                            LexObjectProperty::Boolean(LexBoolean {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("members"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static("DIDs of group members."),
                                ),
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("#communityMember"),
                                    ..Default::default()
                                }),
                                max_length: Some(500usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Group label.")),
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("communityMember"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("A member in a community group."),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("did"), SmolStr::new_static("addedAt")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("addedAt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("When this member was added."),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("did"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("The member's DID.")),
                                format: Some(LexStringFormat::Did),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "The user's community list. Portable across any app implementing the Lexicon.",
                        ),
                    ),
                    key: Some(CowStr::new_static("literal:self")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("groups")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("groups"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Named groups of community members, like AIM's buddy list categories.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#communityGroup"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod community_member_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 AddedAt;
        type Did;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type AddedAt = Unset;
        type Did = Unset;
    }
    ///State transition - sets the `added_at` field to Set
    pub struct SetAddedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetAddedAt<St> {}
    impl<St: State> State for SetAddedAt<St> {
        type AddedAt = Set<members::added_at>;
        type Did = St::Did;
    }
    ///State transition - sets the `did` field to Set
    pub struct SetDid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDid<St> {}
    impl<St: State> State for SetDid<St> {
        type AddedAt = St::AddedAt;
        type Did = Set<members::did>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `added_at` field
        pub struct added_at(());
        ///Marker type for the `did` field
        pub struct did(());
    }
}

/// Builder for constructing an instance of this type.
pub struct CommunityMemberBuilder<
    St: community_member_state::State,
    S: BosStr = DefaultStr,
> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<Datetime>, Option<Did<S>>),
    _type: PhantomData<fn() -> S>,
}

impl CommunityMember<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> CommunityMemberBuilder<community_member_state::Empty, DefaultStr> {
        CommunityMemberBuilder::new()
    }
}

impl<S: BosStr> CommunityMember<S> {
    /// Create a new builder for this type
    pub fn builder() -> CommunityMemberBuilder<community_member_state::Empty, S> {
        CommunityMemberBuilder::builder()
    }
}

impl CommunityMemberBuilder<community_member_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        CommunityMemberBuilder {
            _state: PhantomData,
            _fields: (None, None),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> CommunityMemberBuilder<community_member_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        CommunityMemberBuilder {
            _state: PhantomData,
            _fields: (None, None),
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommunityMemberBuilder<St, S>
where
    St: community_member_state::State,
    St::AddedAt: community_member_state::IsUnset,
{
    /// Set the `addedAt` field (required)
    pub fn added_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> CommunityMemberBuilder<community_member_state::SetAddedAt<St>, S> {
        self._fields.0 = Option::Some(value.into());
        CommunityMemberBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommunityMemberBuilder<St, S>
where
    St: community_member_state::State,
    St::Did: community_member_state::IsUnset,
{
    /// Set the `did` field (required)
    pub fn did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> CommunityMemberBuilder<community_member_state::SetDid<St>, S> {
        self._fields.1 = Option::Some(value.into());
        CommunityMemberBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommunityMemberBuilder<St, S>
where
    St: community_member_state::State,
    St::AddedAt: community_member_state::IsSet,
    St::Did: community_member_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> CommunityMember<S> {
        CommunityMember {
            added_at: self._fields.0.unwrap(),
            did: 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<SmolStr, Data<S>>,
    ) -> CommunityMember<S> {
        CommunityMember {
            added_at: self._fields.0.unwrap(),
            did: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod community_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 Groups;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Groups = Unset;
    }
    ///State transition - sets the `groups` field to Set
    pub struct SetGroups<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetGroups<St> {}
    impl<St: State> State for SetGroups<St> {
        type Groups = Set<members::groups>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `groups` field
        pub struct groups(());
    }
}

/// Builder for constructing an instance of this type.
pub struct CommunityBuilder<St: community_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<Vec<community::CommunityGroup<S>>>,),
    _type: PhantomData<fn() -> S>,
}

impl Community<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> CommunityBuilder<community_state::Empty, DefaultStr> {
        CommunityBuilder::new()
    }
}

impl<S: BosStr> Community<S> {
    /// Create a new builder for this type
    pub fn builder() -> CommunityBuilder<community_state::Empty, S> {
        CommunityBuilder::builder()
    }
}

impl CommunityBuilder<community_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        CommunityBuilder {
            _state: PhantomData,
            _fields: (None,),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> CommunityBuilder<community_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        CommunityBuilder {
            _state: PhantomData,
            _fields: (None,),
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommunityBuilder<St, S>
where
    St: community_state::State,
    St::Groups: community_state::IsUnset,
{
    /// Set the `groups` field (required)
    pub fn groups(
        mut self,
        value: impl Into<Vec<community::CommunityGroup<S>>>,
    ) -> CommunityBuilder<community_state::SetGroups<St>, S> {
        self._fields.0 = Option::Some(value.into());
        CommunityBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommunityBuilder<St, S>
where
    St: community_state::State,
    St::Groups: community_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Community<S> {
        Community {
            groups: self._fields.0.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Community<S> {
        Community {
            groups: self._fields.0.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}