// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: pub.leaflet.content
//
// 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::{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, open_union};
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::pub_leaflet::pages::canvas::Canvas;
use crate::pub_leaflet::pages::linear_document::LinearDocument;
/// Content format for leaflet documents

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Content<S: BosStr = DefaultStr> {
    ///JSON-encoded array of pages. When the inline pages array would be too large to store on the PDS, the pages are uploaded as a blob and referenced here. When set, consumers MUST ignore `pages` and use the decoded blob contents as the page array; the inline `pages` field will be empty or a stub.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob_pages: Option<BlobRef<S>>,
    ///Blobs referenced inside `blobPages`. Load-bearing when `blobPages` is set: the PDS only scans the top level of a record for blob references when deciding what to garbage-collect, so any image/etc. blob now living inside the opaque JSON blob must be mirrored here to remain referenced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blobs: Option<Vec<BlobRef<S>>>,
    pub pages: Vec<ContentPagesItem<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum ContentPagesItem<S: BosStr = DefaultStr> {
    #[serde(rename = "pub.leaflet.pages.linearDocument")]
    LinearDocument(Box<LinearDocument<S>>),
    #[serde(rename = "pub.leaflet.pages.canvas")]
    Canvas(Box<Canvas<S>>),
}

impl<S: BosStr> LexiconSchema for Content<S> {
    fn nsid() -> &'static str {
        "pub.leaflet.content"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_pub_leaflet_content()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.blob_pages {
            {
                let size = value.blob().size;
                if size > 5000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("blob_pages"),
                        max: 5000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.blob_pages {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["application/json"];
                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_pages"),
                        accepted: vec!["application/json".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

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

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

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

impl<S: BosStr> Content<S> {
    /// Create a new builder for this type
    pub fn builder() -> ContentBuilder<content_state::Empty, S> {
        ContentBuilder::builder()
    }
}

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

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

impl<St: content_state::State, S: BosStr> ContentBuilder<St, S> {
    /// Set the `blobPages` field (optional)
    pub fn blob_pages(mut self, value: impl Into<Option<BlobRef<S>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `blobPages` field to an Option value (optional)
    pub fn maybe_blob_pages(mut self, value: Option<BlobRef<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: content_state::State, S: BosStr> ContentBuilder<St, S> {
    /// Set the `blobs` field (optional)
    pub fn blobs(mut self, value: impl Into<Option<Vec<BlobRef<S>>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `blobs` field to an Option value (optional)
    pub fn maybe_blobs(mut self, value: Option<Vec<BlobRef<S>>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> ContentBuilder<St, S>
where
    St: content_state::State,
    St::Pages: content_state::IsUnset,
{
    /// Set the `pages` field (required)
    pub fn pages(
        mut self,
        value: impl Into<Vec<ContentPagesItem<S>>>,
    ) -> ContentBuilder<content_state::SetPages<St>, S> {
        self._fields.2 = Option::Some(value.into());
        ContentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ContentBuilder<St, S>
where
    St: content_state::State,
    St::Pages: content_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Content<S> {
        Content {
            blob_pages: self._fields.0,
            blobs: self._fields.1,
            pages: self._fields.2.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>>) -> Content<S> {
        Content {
            blob_pages: self._fields.0,
            blobs: self._fields.1,
            pages: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_pub_leaflet_content() -> 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("pub.leaflet.content"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("Content format for leaflet documents"),
                    ),
                    required: Some(vec![SmolStr::new_static("pages")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("blobPages"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("blobs"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "Blobs referenced inside `blobPages`. Load-bearing when `blobPages` is set: the PDS only scans the top level of a record for blob references when deciding what to garbage-collect, so any image/etc. blob now living inside the opaque JSON blob must be mirrored here to remain referenced.",
                                    ),
                                ),
                                items: LexArrayItem::Blob(LexBlob { ..Default::default() }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("pages"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::Union(LexRefUnion {
                                    refs: vec![
                                        CowStr::new_static("pub.leaflet.pages.linearDocument"),
                                        CowStr::new_static("pub.leaflet.pages.canvas")
                                    ],
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}