// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: social.clippr.feed.clip
//
// 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::{AtUri, Cid, Datetime, Language, UriValue};
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::com_atproto::repo::strong_ref::StrongRef;
/// Record containing a bookmarked item, or 'clip'.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "social.clippr.feed.clip",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Clip<S: BosStr = DefaultStr> {
    ///Client-declared timestamp when the bookmark is created
    pub created_at: Datetime,
    ///A description of the bookmark's content. This should be ripped from the URL metadata and be static for all records using the URL.
    pub description: S,
    ///Indicates human language of the given URL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub languages: Option<Vec<Language>>,
    ///User-written notes for the bookmark. Public and personal.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<S>,
    ///An array of tags. A format of solely alphanumeric characters and dashes should be used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<StrongRef<S>>>,
    ///The title of the bookmark. If left empty, reuse the URL.
    pub title: S,
    ///Whether the bookmark can be used for feed indexing and aggregation  Defaults to `false`.
    #[serde(default = "_default_clip_unlisted")]
    pub unlisted: bool,
    ///Whether the bookmark has been read by the user  Defaults to `true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_clip_unread")]
    pub unread: Option<bool>,
    ///The URL of the bookmark. Cannot be left empty or be modified after creation.
    pub url: UriValue<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 ClipGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Clip<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ClipRecord;
impl XrpcResp for ClipRecord {
    const NSID: &'static str = "social.clippr.feed.clip";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = ClipGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Clip<S> {
    const NSID: &'static str = "social.clippr.feed.clip";
    type Record = ClipRecord;
}

impl Collection for ClipRecord {
    const NSID: &'static str = "social.clippr.feed.clip";
    type Record = ClipRecord;
}

impl<S: BosStr> LexiconSchema for Clip<S> {
    fn nsid() -> &'static str {
        "social.clippr.feed.clip"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_social_clippr_feed_clip()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.description;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 40960usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 40960usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.description;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 4096usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 4096usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.languages {
            #[allow(unused_comparisons)]
            if value.len() > 5usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("languages"),
                    max: 5usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.notes {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("notes"),
                    max: 100000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.notes {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 10000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("notes"),
                        max: 10000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20480usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 20480usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 2048usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 2048usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.url;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("url"),
                    max: 20000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.url;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 2000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("url"),
                        max: 2000usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

fn _default_clip_unlisted() -> bool {
    false
}

fn _default_clip_unread() -> Option<bool> {
    Some(true)
}

pub mod clip_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 CreatedAt;
        type Description;
        type Title;
        type Unlisted;
        type Url;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Description = Unset;
        type Title = Unset;
        type Unlisted = Unset;
        type Url = Unset;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCreatedAt<St> {}
    impl<St: State> State for SetCreatedAt<St> {
        type CreatedAt = Set<members::created_at>;
        type Description = St::Description;
        type Title = St::Title;
        type Unlisted = St::Unlisted;
        type Url = St::Url;
    }
    ///State transition - sets the `description` field to Set
    pub struct SetDescription<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDescription<St> {}
    impl<St: State> State for SetDescription<St> {
        type CreatedAt = St::CreatedAt;
        type Description = Set<members::description>;
        type Title = St::Title;
        type Unlisted = St::Unlisted;
        type Url = St::Url;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTitle<St> {}
    impl<St: State> State for SetTitle<St> {
        type CreatedAt = St::CreatedAt;
        type Description = St::Description;
        type Title = Set<members::title>;
        type Unlisted = St::Unlisted;
        type Url = St::Url;
    }
    ///State transition - sets the `unlisted` field to Set
    pub struct SetUnlisted<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetUnlisted<St> {}
    impl<St: State> State for SetUnlisted<St> {
        type CreatedAt = St::CreatedAt;
        type Description = St::Description;
        type Title = St::Title;
        type Unlisted = Set<members::unlisted>;
        type Url = St::Url;
    }
    ///State transition - sets the `url` field to Set
    pub struct SetUrl<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetUrl<St> {}
    impl<St: State> State for SetUrl<St> {
        type CreatedAt = St::CreatedAt;
        type Description = St::Description;
        type Title = St::Title;
        type Unlisted = St::Unlisted;
        type Url = Set<members::url>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `description` field
        pub struct description(());
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `unlisted` field
        pub struct unlisted(());
        ///Marker type for the `url` field
        pub struct url(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ClipBuilder<St: clip_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<S>,
        Option<Vec<Language>>,
        Option<S>,
        Option<Vec<StrongRef<S>>>,
        Option<S>,
        Option<bool>,
        Option<bool>,
        Option<UriValue<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Clip<S> {
    /// Create a new builder for this type
    pub fn builder() -> ClipBuilder<clip_state::Empty, S> {
        ClipBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ClipBuilder<St, S>
where
    St: clip_state::State,
    St::CreatedAt: clip_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> ClipBuilder<clip_state::SetCreatedAt<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ClipBuilder<St, S>
where
    St: clip_state::State,
    St::Description: clip_state::IsUnset,
{
    /// Set the `description` field (required)
    pub fn description(
        mut self,
        value: impl Into<S>,
    ) -> ClipBuilder<clip_state::SetDescription<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: clip_state::State, S: BosStr> ClipBuilder<St, S> {
    /// Set the `languages` field (optional)
    pub fn languages(mut self, value: impl Into<Option<Vec<Language>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `languages` field to an Option value (optional)
    pub fn maybe_languages(mut self, value: Option<Vec<Language>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: clip_state::State, S: BosStr> ClipBuilder<St, S> {
    /// Set the `notes` field (optional)
    pub fn notes(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `notes` field to an Option value (optional)
    pub fn maybe_notes(mut self, value: Option<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: clip_state::State, S: BosStr> ClipBuilder<St, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<StrongRef<S>>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `tags` field to an Option value (optional)
    pub fn maybe_tags(mut self, value: Option<Vec<StrongRef<S>>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> ClipBuilder<St, S>
where
    St: clip_state::State,
    St::Title: clip_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<S>,
    ) -> ClipBuilder<clip_state::SetTitle<St>, S> {
        self._fields.5 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ClipBuilder<St, S>
where
    St: clip_state::State,
    St::Unlisted: clip_state::IsUnset,
{
    /// Set the `unlisted` field (required)
    pub fn unlisted(
        mut self,
        value: impl Into<bool>,
    ) -> ClipBuilder<clip_state::SetUnlisted<St>, S> {
        self._fields.6 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: clip_state::State, S: BosStr> ClipBuilder<St, S> {
    /// Set the `unread` field (optional)
    pub fn unread(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `unread` field to an Option value (optional)
    pub fn maybe_unread(mut self, value: Option<bool>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St, S: BosStr> ClipBuilder<St, S>
where
    St: clip_state::State,
    St::Url: clip_state::IsUnset,
{
    /// Set the `url` field (required)
    pub fn url(
        mut self,
        value: impl Into<UriValue<S>>,
    ) -> ClipBuilder<clip_state::SetUrl<St>, S> {
        self._fields.8 = Option::Some(value.into());
        ClipBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ClipBuilder<St, S>
where
    St: clip_state::State,
    St::CreatedAt: clip_state::IsSet,
    St::Description: clip_state::IsSet,
    St::Title: clip_state::IsSet,
    St::Unlisted: clip_state::IsSet,
    St::Url: clip_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Clip<S> {
        Clip {
            created_at: self._fields.0.unwrap(),
            description: self._fields.1.unwrap(),
            languages: self._fields.2,
            notes: self._fields.3,
            tags: self._fields.4,
            title: self._fields.5.unwrap(),
            unlisted: self._fields.6.unwrap(),
            unread: self._fields.7.or_else(|| Some(true)),
            url: self._fields.8.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>>) -> Clip<S> {
        Clip {
            created_at: self._fields.0.unwrap(),
            description: self._fields.1.unwrap(),
            languages: self._fields.2,
            notes: self._fields.3,
            tags: self._fields.4,
            title: self._fields.5.unwrap(),
            unlisted: self._fields.6.unwrap(),
            unread: self._fields.7.or_else(|| Some(true)),
            url: self._fields.8.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_social_clippr_feed_clip() -> 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("social.clippr.feed.clip"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Record containing a bookmarked item, or 'clip'.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("url"), SmolStr::new_static("title"),
                                SmolStr::new_static("description"),
                                SmolStr::new_static("unlisted"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when the bookmark is created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "A description of the bookmark's content. This should be ripped from the URL metadata and be static for all records using the URL.",
                                        ),
                                    ),
                                    max_length: Some(40960usize),
                                    max_graphemes: Some(4096usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("languages"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Indicates human language of the given URL",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Language),
                                        ..Default::default()
                                    }),
                                    max_length: Some(5usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("notes"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "User-written notes for the bookmark. Public and personal.",
                                        ),
                                    ),
                                    max_length: Some(100000usize),
                                    max_graphemes: Some(10000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "An array of tags. A format of solely alphanumeric characters and dashes should be used.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The title of the bookmark. If left empty, reuse the URL.",
                                        ),
                                    ),
                                    max_length: Some(20480usize),
                                    max_graphemes: Some(2048usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("unlisted"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("unread"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("url"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The URL of the bookmark. Cannot be left empty or be modified after creation.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    max_length: Some(20000usize),
                                    max_graphemes: Some(2000usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}