// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: store.88x31.button
//
// 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::blob::BlobRef;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{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};
/// Record containing an 88x31 button.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Button<'a> {
    ///Alt text description of the button, for accessibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub alt: Option<CowStr<'a>>,
    #[serde(borrow)]
    pub blob: BlobRef<'a>,
    ///Hypertext reference (link) for the button.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub href: Option<CowStr<'a>>,
    ///Client-declared timestamp when this button was originally created.
    pub posted_at: Datetime,
    ///Title text description of the button, for flavor.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub title: Option<CowStr<'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 ButtonGetRecordOutput<'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: Button<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ButtonRecord;
impl XrpcResp for ButtonRecord {
    const NSID: &'static str = "store.88x31.button";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ButtonGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Button<'_> {
    const NSID: &'static str = "store.88x31.button";
    type Record = ButtonRecord;
}

impl Collection for ButtonRecord {
    const NSID: &'static str = "store.88x31.button";
    type Record = ButtonRecord;
}

impl<'a> LexiconSchema for Button<'a> {
    fn nsid() -> &'static str {
        "store.88x31.button"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_store_88x31_button()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.alt {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("alt"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.alt {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("alt"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.blob;
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("blob"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.blob;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/*"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("blob"),
                        accepted: vec!["image/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        if let Some(ref value) = self.href {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("href"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.href {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("href"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.title {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.title {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 300usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod button_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 Blob;
        type PostedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Blob = Unset;
        type PostedAt = Unset;
    }
    ///State transition - sets the `blob` field to Set
    pub struct SetBlob<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetBlob<S> {}
    impl<S: State> State for SetBlob<S> {
        type Blob = Set<members::blob>;
        type PostedAt = S::PostedAt;
    }
    ///State transition - sets the `posted_at` field to Set
    pub struct SetPostedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPostedAt<S> {}
    impl<S: State> State for SetPostedAt<S> {
        type Blob = S::Blob;
        type PostedAt = Set<members::posted_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `blob` field
        pub struct blob(());
        ///Marker type for the `posted_at` field
        pub struct posted_at(());
    }
}

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

impl<'a> Button<'a> {
    /// Create a new builder for this type
    pub fn new() -> ButtonBuilder<'a, button_state::Empty> {
        ButtonBuilder::new()
    }
}

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

impl<'a, S: button_state::State> ButtonBuilder<'a, S> {
    /// Set the `alt` field (optional)
    pub fn alt(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `alt` field to an Option value (optional)
    pub fn maybe_alt(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S> ButtonBuilder<'a, S>
where
    S: button_state::State,
    S::Blob: button_state::IsUnset,
{
    /// Set the `blob` field (required)
    pub fn blob(
        mut self,
        value: impl Into<BlobRef<'a>>,
    ) -> ButtonBuilder<'a, button_state::SetBlob<S>> {
        self._fields.1 = Option::Some(value.into());
        ButtonBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: button_state::State> ButtonBuilder<'a, S> {
    /// Set the `href` field (optional)
    pub fn href(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `href` field to an Option value (optional)
    pub fn maybe_href(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S> ButtonBuilder<'a, S>
where
    S: button_state::State,
    S::PostedAt: button_state::IsUnset,
{
    /// Set the `postedAt` field (required)
    pub fn posted_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> ButtonBuilder<'a, button_state::SetPostedAt<S>> {
        self._fields.3 = Option::Some(value.into());
        ButtonBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: button_state::State> ButtonBuilder<'a, S> {
    /// Set the `title` field (optional)
    pub fn title(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `title` field to an Option value (optional)
    pub fn maybe_title(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> ButtonBuilder<'a, S>
where
    S: button_state::State,
    S::Blob: button_state::IsSet,
    S::PostedAt: button_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Button<'a> {
        Button {
            alt: self._fields.0,
            blob: self._fields.1.unwrap(),
            href: self._fields.2,
            posted_at: self._fields.3.unwrap(),
            title: self._fields.4,
            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>,
        >,
    ) -> Button<'a> {
        Button {
            alt: self._fields.0,
            blob: self._fields.1.unwrap(),
            href: self._fields.2,
            posted_at: self._fields.3.unwrap(),
            title: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_store_88x31_button() -> 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("store.88x31.button"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("Record containing an 88x31 button."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("blob"), SmolStr::new_static("postedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("alt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Alt text description of the button, for accessibility.",
                                        ),
                                    ),
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("blob"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("href"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Hypertext reference (link) for the button.",
                                        ),
                                    ),
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("postedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when this button was originally created.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Title text description of the button, for flavor.",
                                        ),
                                    ),
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}