// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: download.darkworld.content.markdown
//
// 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::download_darkworld::content::markdown;
/// blob keyed by ref in the body

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ImageRef<S: BosStr = DefaultStr> {
    pub blob: BlobRef<S>,
    ///key used to reference the blob
    pub image_ref: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// markdown for rendering in darkworld.download/blog

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Markdown<S: BosStr = DefaultStr> {
    ///markdown source ![alt](imageRef) to embed images
    pub body: S,
    ///Images referenced in the body with ![alt](imageRef)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub images: Option<Vec<markdown::ImageRef<S>>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

impl<S: BosStr> LexiconSchema for ImageRef<S> {
    fn nsid() -> &'static str {
        "download.darkworld.content.markdown"
    }
    fn def_name() -> &'static str {
        "imageRef"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_download_darkworld_content_markdown()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.blob;
            {
                let size = value.blob().size;
                if size > 5000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("blob"),
                        max: 5000000usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let 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(),
                    });
                }
            }
        }
        {
            let value = &self.image_ref;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("image_ref"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.image_ref;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 128usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("image_ref"),
                        max: 128usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Markdown<S> {
    fn nsid() -> &'static str {
        "download.darkworld.content.markdown"
    }
    fn def_name() -> &'static str {
        "markdown"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_download_darkworld_content_markdown()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.body;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("body"),
                    max: 1000000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.images {
            #[allow(unused_comparisons)]
            if value.len() > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("images"),
                    max: 128usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

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

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

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

impl<S: BosStr> ImageRef<S> {
    /// Create a new builder for this type
    pub fn builder() -> ImageRefBuilder<image_ref_state::Empty, S> {
        ImageRefBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ImageRefBuilder<St, S>
where
    St: image_ref_state::State,
    St::Blob: image_ref_state::IsUnset,
{
    /// Set the `blob` field (required)
    pub fn blob(
        mut self,
        value: impl Into<BlobRef<S>>,
    ) -> ImageRefBuilder<image_ref_state::SetBlob<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ImageRefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ImageRefBuilder<St, S>
where
    St: image_ref_state::State,
    St::ImageRef: image_ref_state::IsUnset,
{
    /// Set the `imageRef` field (required)
    pub fn image_ref(
        mut self,
        value: impl Into<S>,
    ) -> ImageRefBuilder<image_ref_state::SetImageRef<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ImageRefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ImageRefBuilder<St, S>
where
    St: image_ref_state::State,
    St::Blob: image_ref_state::IsSet,
    St::ImageRef: image_ref_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ImageRef<S> {
        ImageRef {
            blob: self._fields.0.unwrap(),
            image_ref: self._fields.1.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>>) -> ImageRef<S> {
        ImageRef {
            blob: self._fields.0.unwrap(),
            image_ref: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_download_darkworld_content_markdown() -> 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("download.darkworld.content.markdown"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("imageRef"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("blob keyed by ref in the body"),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("imageRef"), SmolStr::new_static("blob")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("blob"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("imageRef"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("key used to reference the blob"),
                                ),
                                max_length: Some(512usize),
                                max_graphemes: Some(128usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("markdown"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "markdown for rendering in darkworld.download/blog",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("body")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("body"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "markdown source ![alt](imageRef) to embed images",
                                    ),
                                ),
                                max_length: Some(1000000usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("images"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "Images referenced in the body with ![alt](imageRef)",
                                    ),
                                ),
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("#imageRef"),
                                    ..Default::default()
                                }),
                                max_length: Some(128usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}