// @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, 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::string::UriValue;
use jacquard_common::types::value::Data;
use jacquard_derive::IntoStatic;
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct WebBookmark<S: BosStr = DefaultStr> {
    ///Page description/excerpt
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///The URL of the bookmarked page
    pub href: UriValue<S>,
    ///Open Graph image for the page
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preview: Option<BlobRef<S>>,
    ///Name of the website
    #[serde(skip_serializing_if = "Option::is_none")]
    pub site_name: Option<S>,
    ///Page title
    pub title: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

impl<S: BosStr> LexiconSchema for WebBookmark<S> {
    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 Href;
        type Title;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Href = Unset;
        type Title = Unset;
    }
    ///State transition - sets the `href` field to Set
    pub struct SetHref<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetHref<St> {}
    impl<St: State> State for SetHref<St> {
        type Href = Set<members::href>;
        type Title = St::Title;
    }
    ///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 Href = St::Href;
        type Title = Set<members::title>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `href` field
        pub struct href(());
        ///Marker type for the `title` field
        pub struct title(());
    }
}

/// Builder for constructing an instance of this type.
pub struct WebBookmarkBuilder<St: web_bookmark_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<UriValue<S>>, Option<BlobRef<S>>, Option<S>, Option<S>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

impl<St: web_bookmark_state::State, S: BosStr> WebBookmarkBuilder<St, S> {
    /// Set the `preview` field (optional)
    pub fn preview(mut self, value: impl Into<Option<BlobRef<S>>>) -> 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<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: web_bookmark_state::State, S: BosStr> WebBookmarkBuilder<St, S> {
    /// Set the `siteName` field (optional)
    pub fn site_name(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

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

impl<St, S: BosStr> WebBookmarkBuilder<St, S>
where
    St: web_bookmark_state::State,
    St::Href: web_bookmark_state::IsSet,
    St::Title: web_bookmark_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> WebBookmark<S> {
        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<SmolStr, Data<S>>,
    ) -> WebBookmark<S> {
        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()
    }
}