// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.offprint.block.imageGrid
//
// 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::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};
use crate::app_offprint::block::image::AspectRatio;
use crate::app_offprint::block::image_grid;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct GridImage<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alt: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aspect_ratio: Option<AspectRatio<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob: Option<BlobRef<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ImageGrid<S: BosStr = DefaultStr> {
    ///Aspect ratio mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aspect_ratio: Option<S>,
    ///Grid caption
    #[serde(skip_serializing_if = "Option::is_none")]
    pub caption: Option<S>,
    ///Number of rows in the grid
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grid_rows: Option<i64>,
    ///Array of images in the grid (2-6)
    pub images: Vec<image_grid::GridImage<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

impl<S: BosStr> LexiconSchema for GridImage<S> {
    fn nsid() -> &'static str {
        "app.offprint.block.imageGrid"
    }
    fn def_name() -> &'static str {
        "gridImage"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_offprint_block_imageGrid()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        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,
                    });
                }
            }
        }
        if let Some(ref value) = self.blob {
            {
                let size = value.blob().size;
                if size > 10000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("blob"),
                        max: 10000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref 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(),
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for ImageGrid<S> {
    fn nsid() -> &'static str {
        "app.offprint.block.imageGrid"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_offprint_block_imageGrid()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.grid_rows {
            if *value > 2i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("grid_rows"),
                    max: 2i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.grid_rows {
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("grid_rows"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.images;
            #[allow(unused_comparisons)]
            if value.len() > 6usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("images"),
                    max: 6usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.images;
            #[allow(unused_comparisons)]
            if value.len() < 2usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("images"),
                    min: 2usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

fn lexicon_doc_app_offprint_block_imageGrid() -> 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.imageGrid"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("gridImage"),
                LexUserType::Object(LexObject {
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("alt"),
                            LexObjectProperty::String(LexString {
                                max_graphemes: Some(300usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("aspectRatio"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static(
                                    "app.offprint.block.image#aspectRatio",
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("blob"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("images")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("aspectRatio"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Aspect ratio mode")),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("caption"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Grid caption")),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("gridRows"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(1i64),
                                maximum: Some(2i64),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("images"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static("Array of images in the grid (2-6)"),
                                ),
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("#gridImage"),
                                    ..Default::default()
                                }),
                                min_length: Some(2usize),
                                max_length: Some(6usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

/// Builder for constructing an instance of this type.
pub struct ImageGridBuilder<St: image_grid_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<S>, Option<i64>, Option<Vec<image_grid::GridImage<S>>>),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> ImageGrid<S> {
    /// Create a new builder for this type
    pub fn builder() -> ImageGridBuilder<image_grid_state::Empty, S> {
        ImageGridBuilder::builder()
    }
}

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

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

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

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

impl<St: image_grid_state::State, S: BosStr> ImageGridBuilder<St, S> {
    /// Set the `gridRows` field (optional)
    pub fn grid_rows(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `gridRows` field to an Option value (optional)
    pub fn maybe_grid_rows(mut self, value: Option<i64>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> ImageGridBuilder<St, S>
where
    St: image_grid_state::State,
    St::Images: image_grid_state::IsUnset,
{
    /// Set the `images` field (required)
    pub fn images(
        mut self,
        value: impl Into<Vec<image_grid::GridImage<S>>>,
    ) -> ImageGridBuilder<image_grid_state::SetImages<St>, S> {
        self._fields.3 = Option::Some(value.into());
        ImageGridBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ImageGridBuilder<St, S>
where
    St: image_grid_state::State,
    St::Images: image_grid_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ImageGrid<S> {
        ImageGrid {
            aspect_ratio: self._fields.0,
            caption: self._fields.1,
            grid_rows: self._fields.2,
            images: self._fields.3.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>>,
    ) -> ImageGrid<S> {
        ImageGrid {
            aspect_ratio: self._fields.0,
            caption: self._fields.1,
            grid_rows: self._fields.2,
            images: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}