// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.offprint.block.webEmbed
//
// 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 WebEmbed<S: BosStr = DefaultStr> {
    ///Horizontal alignment
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alignment: Option<S>,
    ///Page description/excerpt
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Native embed height in pixels
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embed_height: Option<i64>,
    ///oEmbed URL for iframe embedding
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embed_url: Option<UriValue<S>>,
    ///Native embed width in pixels
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embed_width: Option<i64>,
    ///The URL of the embedded page
    pub href: UriValue<S>,
    ///Screenshot of the embedded content (1280×720px)
    #[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
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<S>,
    ///CSS width value (e.g., "100%", "75%". "50%" minimum)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub width: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

impl<S: BosStr> LexiconSchema for WebEmbed<S> {
    fn nsid() -> &'static str {
        "app.offprint.block.webEmbed"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_offprint_block_webEmbed()
    }
    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.embed_height {
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("embed_height"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.embed_width {
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("embed_width"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        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,
                    });
                }
            }
        }
        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 web_embed_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;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Href = 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>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `href` field
        pub struct href(());
    }
}

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

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

impl<S: BosStr> WebEmbed<S> {
    /// Create a new builder for this type
    pub fn builder() -> WebEmbedBuilder<web_embed_state::Empty, S> {
        WebEmbedBuilder::builder()
    }
}

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

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

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

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

impl<St: web_embed_state::State, S: BosStr> WebEmbedBuilder<St, S> {
    /// Set the `embedHeight` field (optional)
    pub fn embed_height(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `embedHeight` field to an Option value (optional)
    pub fn maybe_embed_height(mut self, value: Option<i64>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: web_embed_state::State, S: BosStr> WebEmbedBuilder<St, S> {
    /// Set the `embedUrl` field (optional)
    pub fn embed_url(mut self, value: impl Into<Option<UriValue<S>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `embedUrl` field to an Option value (optional)
    pub fn maybe_embed_url(mut self, value: Option<UriValue<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: web_embed_state::State, S: BosStr> WebEmbedBuilder<St, S> {
    /// Set the `embedWidth` field (optional)
    pub fn embed_width(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `embedWidth` field to an Option value (optional)
    pub fn maybe_embed_width(mut self, value: Option<i64>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

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

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

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

impl<St: web_embed_state::State, S: BosStr> WebEmbedBuilder<St, S> {
    /// Set the `width` field (optional)
    pub fn width(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.9 = value.into();
        self
    }
    /// Set the `width` field to an Option value (optional)
    pub fn maybe_width(mut self, value: Option<S>) -> Self {
        self._fields.9 = value;
        self
    }
}

impl<St, S: BosStr> WebEmbedBuilder<St, S>
where
    St: web_embed_state::State,
    St::Href: web_embed_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> WebEmbed<S> {
        WebEmbed {
            alignment: self._fields.0,
            description: self._fields.1,
            embed_height: self._fields.2,
            embed_url: self._fields.3,
            embed_width: self._fields.4,
            href: self._fields.5.unwrap(),
            preview: self._fields.6,
            site_name: self._fields.7,
            title: self._fields.8,
            width: self._fields.9,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> WebEmbed<S> {
        WebEmbed {
            alignment: self._fields.0,
            description: self._fields.1,
            embed_height: self._fields.2,
            embed_url: self._fields.3,
            embed_width: self._fields.4,
            href: self._fields.5.unwrap(),
            preview: self._fields.6,
            site_name: self._fields.7,
            title: self._fields.8,
            width: self._fields.9,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_offprint_block_webEmbed() -> 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.webEmbed"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("href")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("alignment"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Horizontal alignment"),
                                ),
                                ..Default::default()
                            }),
                        );
                        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("embedHeight"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(1i64),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("embedUrl"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("oEmbed URL for iframe embedding"),
                                ),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("embedWidth"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(1i64),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("href"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The URL of the embedded 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.insert(
                            SmolStr::new_static("width"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "CSS width value (e.g., \"100%\", \"75%\". \"50%\" minimum)",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}