// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct CommunityGroup<'a> {
    ///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.
    #[serde(borrow)]
    pub members: Vec<community::CommunityMember<'a>>,
    ///Group label.
    #[serde(borrow)]
    pub name: CowStr<'a>,
}

/// A member in a community group.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct CommunityMember<'a> {
    ///When this member was added.
    pub added_at: Datetime,
    ///The member's DID.
    #[serde(borrow)]
    pub did: Did<'a>,
}

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Community<'a> {
    ///Named groups of community members, like AIM's buddy list categories.
    #[serde(borrow)]
    pub groups: Vec<community::CommunityGroup<'a>>,
}

/// 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<'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: Community<'a>,
}

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

impl<'a> LexiconSchema for CommunityGroup<'a> {
    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<'a> LexiconSchema for CommunityMember<'a> {
    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<'de> = CommunityGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Community<'_> {
    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<'a> LexiconSchema for Community<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetMembers<S> {}
    impl<S: State> State for SetMembers<S> {
        type Members = Set<members::members>;
        type Name = S::Name;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetName<S> {}
    impl<S: State> State for SetName<S> {
        type Members = S::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<'a, S: community_group_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<bool>,
        Option<Vec<community::CommunityMember<'a>>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> CommunityGroupBuilder<'a, S>
where
    S: community_group_state::State,
    S::Members: community_group_state::IsSet,
    S::Name: community_group_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> CommunityGroup<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> CommunityGroup<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAddedAt<S> {}
    impl<S: State> State for SetAddedAt<S> {
        type AddedAt = Set<members::added_at>;
        type Did = S::Did;
    }
    ///State transition - sets the `did` field to Set
    pub struct SetDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDid<S> {}
    impl<S: State> State for SetDid<S> {
        type AddedAt = S::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<'a, S: community_member_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Datetime>, Option<Did<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> CommunityMemberBuilder<'a, S>
where
    S: community_member_state::State,
    S::AddedAt: community_member_state::IsSet,
    S::Did: community_member_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> CommunityMember<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> CommunityMember<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetGroups<S> {}
    impl<S: State> State for SetGroups<S> {
        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<'a, S: community_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Vec<community::CommunityGroup<'a>>>,),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

impl<'a, S> CommunityBuilder<'a, S>
where
    S: community_state::State,
    S::Groups: community_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Community<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Community<'a> {
        Community {
            groups: self._fields.0.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}