// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::blob::BlobRef;
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};
use crate::app_offprint::block::image::AspectRatio;
use crate::app_offprint::block::image_grid;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct GridImage<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub alt: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub aspect_ratio: Option<AspectRatio<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub blob: Option<BlobRef<'a>>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ImageGrid<'a> {
    ///Aspect ratio mode
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub aspect_ratio: Option<CowStr<'a>>,
    ///Grid caption
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub caption: Option<CowStr<'a>>,
    ///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)
    #[serde(borrow)]
    pub images: Vec<image_grid::GridImage<'a>>,
}

impl<'a> LexiconSchema for GridImage<'a> {
    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<'a> LexiconSchema for ImageGrid<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetImages<S> {}
    impl<S: State> State for SetImages<S> {
        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<'a, S: image_grid_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<i64>,
        Option<Vec<image_grid::GridImage<'a>>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

impl<'a, S: image_grid_state::State> ImageGridBuilder<'a, S> {
    /// Set the `aspectRatio` field (optional)
    pub fn aspect_ratio(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

impl<'a, S> ImageGridBuilder<'a, S>
where
    S: image_grid_state::State,
    S::Images: image_grid_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ImageGrid<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> ImageGrid<'a> {
        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),
        }
    }
}