// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.offprint.block.webBookmark
//
// 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::string::UriValue;
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};

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct WebBookmark<'a> {
    ///Page description/excerpt
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///The URL of the bookmarked page
    #[serde(borrow)]
    pub href: UriValue<'a>,
    ///Open Graph image for the page
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub preview: Option<BlobRef<'a>>,
    ///Name of the website
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub site_name: Option<CowStr<'a>>,
    ///Page title
    #[serde(borrow)]
    pub title: CowStr<'a>,
}

impl<'a> LexiconSchema for WebBookmark<'a> {
    fn nsid() -> &'static str {
        "app.offprint.block.webBookmark"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_offprint_block_webBookmark()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 1000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 1000usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.preview {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("preview"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.preview {
            {
                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("preview"),
                        accepted: vec!["image/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        if let Some(ref value) = self.site_name {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 100usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("site_name"),
                        max: 100usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let 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 web_bookmark_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 Title;
        type Href;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Title = Unset;
        type Href = Unset;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTitle<S> {}
    impl<S: State> State for SetTitle<S> {
        type Title = Set<members::title>;
        type Href = S::Href;
    }
    ///State transition - sets the `href` field to Set
    pub struct SetHref<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetHref<S> {}
    impl<S: State> State for SetHref<S> {
        type Title = S::Title;
        type Href = Set<members::href>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `title` field
        pub struct title(());
        ///Marker type for the `href` field
        pub struct href(());
    }
}

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

impl<'a> WebBookmark<'a> {
    /// Create a new builder for this type
    pub fn new() -> WebBookmarkBuilder<'a, web_bookmark_state::Empty> {
        WebBookmarkBuilder::new()
    }
}

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

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

impl<'a, S> WebBookmarkBuilder<'a, S>
where
    S: web_bookmark_state::State,
    S::Href: web_bookmark_state::IsUnset,
{
    /// Set the `href` field (required)
    pub fn href(
        mut self,
        value: impl Into<UriValue<'a>>,
    ) -> WebBookmarkBuilder<'a, web_bookmark_state::SetHref<S>> {
        self._fields.1 = Option::Some(value.into());
        WebBookmarkBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: web_bookmark_state::State> WebBookmarkBuilder<'a, S> {
    /// Set the `preview` field (optional)
    pub fn preview(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `preview` field to an Option value (optional)
    pub fn maybe_preview(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: web_bookmark_state::State> WebBookmarkBuilder<'a, S> {
    /// Set the `siteName` field (optional)
    pub fn site_name(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `siteName` field to an Option value (optional)
    pub fn maybe_site_name(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> WebBookmarkBuilder<'a, S>
where
    S: web_bookmark_state::State,
    S::Title: web_bookmark_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> WebBookmarkBuilder<'a, web_bookmark_state::SetTitle<S>> {
        self._fields.4 = Option::Some(value.into());
        WebBookmarkBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> WebBookmarkBuilder<'a, S>
where
    S: web_bookmark_state::State,
    S::Title: web_bookmark_state::IsSet,
    S::Href: web_bookmark_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> WebBookmark<'a> {
        WebBookmark {
            description: self._fields.0,
            href: self._fields.1.unwrap(),
            preview: self._fields.2,
            site_name: self._fields.3,
            title: self._fields.4.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>,
        >,
    ) -> WebBookmark<'a> {
        WebBookmark {
            description: self._fields.0,
            href: self._fields.1.unwrap(),
            preview: self._fields.2,
            site_name: self._fields.3,
            title: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_offprint_block_webBookmark() -> 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.offprint.block.webBookmark"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("href"), SmolStr::new_static("title")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("description"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Page description/excerpt"),
                                ),
                                max_graphemes: Some(1000usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("href"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The URL of the bookmarked page"),
                                ),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("preview"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("siteName"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Name of the website"),
                                ),
                                max_graphemes: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("title"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Page title")),
                                max_graphemes: Some(300usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}