// @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, 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::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::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};
/// Record containing an 88x31 button.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "store.88x31.button",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Button<S: BosStr = DefaultStr> {
    ///Alt text description of the button, for accessibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alt: Option<S>,
    pub blob: BlobRef<S>,
    ///Hypertext reference (link) for the button.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub href: Option<S>,
    ///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")]
    pub title: Option<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 ButtonGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Button<S>,
}

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

/// 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<S: BosStr> = ButtonGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Button<S> {
    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<S: BosStr> LexiconSchema for Button<S> {
    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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetBlob<St> {}
    impl<St: State> State for SetBlob<St> {
        type Blob = Set<members::blob>;
        type PostedAt = St::PostedAt;
    }
    ///State transition - sets the `posted_at` field to Set
    pub struct SetPostedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPostedAt<St> {}
    impl<St: State> State for SetPostedAt<St> {
        type Blob = St::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<St: button_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<BlobRef<S>>, Option<S>, Option<Datetime>, Option<S>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

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

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

impl<St, S: BosStr> ButtonBuilder<St, S>
where
    St: button_state::State,
    St::Blob: button_state::IsSet,
    St::PostedAt: button_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Button<S> {
        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<SmolStr, Data<S>>) -> Button<S> {
        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()
    }
}