// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: com.shinolabs.pinksea.oekaki
//
// 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
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::com_atproto::repo::strong_ref::StrongRef;
use crate::com_shinolabs::pinksea::oekaki;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Image<S: BosStr = DefaultStr> {
    ///The actual atproto image blob.
    pub blob: BlobRef<S>,
    pub image_link: oekaki::ImageLink<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A link to the image, it can be either directly to the PDS or to a CDN.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ImageLink<S: BosStr = DefaultStr> {
    ///Alt text description of the image, for accessibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alt: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// An oekaki post.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "com.shinolabs.pinksea.oekaki",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Oekaki<S: BosStr = DefaultStr> {
    ///The timestamp of creation.
    pub created_at: Datetime,
    pub image: oekaki::Image<S>,
    ///What this oekaki post is a response to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_response_to: Option<StrongRef<S>>,
    ///Is this oekaki NSFW?
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nsfw: Option<bool>,
    ///An array of tags this image had.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct OekakiGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Oekaki<S>,
}

impl<S: BosStr> Oekaki<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, OekakiRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

impl<S: BosStr> LexiconSchema for Image<S> {
    fn nsid() -> &'static str {
        "com.shinolabs.pinksea.oekaki"
    }
    fn def_name() -> &'static str {
        "image"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_com_shinolabs_pinksea_oekaki()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.blob;
            {
                let size = value.blob().size;
                if size > 1048576usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("blob"),
                        max: 1048576usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.blob;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/png"];
                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/png".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for ImageLink<S> {
    fn nsid() -> &'static str {
        "com.shinolabs.pinksea.oekaki"
    }
    fn def_name() -> &'static str {
        "imageLink"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_com_shinolabs_pinksea_oekaki()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

/// Marker type for deserializing records from this collection.

#[derive(Debug, Serialize, Deserialize)]
pub struct OekakiRecord;
impl XrpcResp for OekakiRecord {
    const NSID: &'static str = "com.shinolabs.pinksea.oekaki";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = OekakiGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<OekakiGetRecordOutput<S>> for Oekaki<S> {
    fn from(output: OekakiGetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Oekaki<S> {
    const NSID: &'static str = "com.shinolabs.pinksea.oekaki";
    type Record = OekakiRecord;
}

impl Collection for OekakiRecord {
    const NSID: &'static str = "com.shinolabs.pinksea.oekaki";
    type Record = OekakiRecord;
}

impl<S: BosStr> LexiconSchema for Oekaki<S> {
    fn nsid() -> &'static str {
        "com.shinolabs.pinksea.oekaki"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_com_shinolabs_pinksea_oekaki()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.tags {
            #[allow(unused_comparisons)]
            if value.len() > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("tags"),
                    max: 10usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

pub mod image_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 ImageLink;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Blob = Unset;
        type ImageLink = 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 ImageLink = St::ImageLink;
    }
    ///State transition - sets the `image_link` field to Set
    pub struct SetImageLink<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetImageLink<St> {}
    impl<St: State> State for SetImageLink<St> {
        type Blob = St::Blob;
        type ImageLink = Set<members::image_link>;
    }
    /// 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_link` field
        pub struct image_link(());
    }
}

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

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

impl<S: BosStr> Image<S> {
    /// Create a new builder for this type
    pub fn builder() -> ImageBuilder<image_state::Empty, S> {
        ImageBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> ImageBuilder<St, S>
where
    St: image_state::State,
    St::ImageLink: image_state::IsUnset,
{
    /// Set the `imageLink` field (required)
    pub fn image_link(
        mut self,
        value: impl Into<oekaki::ImageLink<S>>,
    ) -> ImageBuilder<image_state::SetImageLink<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ImageBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

fn lexicon_doc_com_shinolabs_pinksea_oekaki() -> 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("com.shinolabs.pinksea.oekaki"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("image"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("blob"), SmolStr::new_static("imageLink")
                        ],
                    ),
                    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("imageLink"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static("#imageLink"),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("imageLink"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A link to the image, it can be either directly to the PDS or to a CDN.",
                        ),
                    ),
                    required: Some(vec![]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("alt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Alt text description of the image, for accessibility.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(CowStr::new_static("An oekaki post.")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("image"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The timestamp of creation."),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("image"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#image"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("inResponseTo"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("nsfw"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("An array of tags this image had."),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(640usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

/// Builder for constructing an instance of this type.
pub struct OekakiBuilder<St: oekaki_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<oekaki::Image<S>>,
        Option<StrongRef<S>>,
        Option<bool>,
        Option<Vec<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Oekaki<S> {
    /// Create a new builder for this type
    pub fn builder() -> OekakiBuilder<oekaki_state::Empty, S> {
        OekakiBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> OekakiBuilder<St, S>
where
    St: oekaki_state::State,
    St::CreatedAt: oekaki_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> OekakiBuilder<oekaki_state::SetCreatedAt<St>, S> {
        self._fields.0 = Option::Some(value.into());
        OekakiBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> OekakiBuilder<St, S>
where
    St: oekaki_state::State,
    St::Image: oekaki_state::IsUnset,
{
    /// Set the `image` field (required)
    pub fn image(
        mut self,
        value: impl Into<oekaki::Image<S>>,
    ) -> OekakiBuilder<oekaki_state::SetImage<St>, S> {
        self._fields.1 = Option::Some(value.into());
        OekakiBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: oekaki_state::State, S: BosStr> OekakiBuilder<St, S> {
    /// Set the `inResponseTo` field (optional)
    pub fn in_response_to(mut self, value: impl Into<Option<StrongRef<S>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `inResponseTo` field to an Option value (optional)
    pub fn maybe_in_response_to(mut self, value: Option<StrongRef<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: oekaki_state::State, S: BosStr> OekakiBuilder<St, S> {
    /// Set the `nsfw` field (optional)
    pub fn nsfw(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `nsfw` field to an Option value (optional)
    pub fn maybe_nsfw(mut self, value: Option<bool>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: oekaki_state::State, S: BosStr> OekakiBuilder<St, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `tags` field to an Option value (optional)
    pub fn maybe_tags(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> OekakiBuilder<St, S>
where
    St: oekaki_state::State,
    St::CreatedAt: oekaki_state::IsSet,
    St::Image: oekaki_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Oekaki<S> {
        Oekaki {
            created_at: self._fields.0.unwrap(),
            image: self._fields.1.unwrap(),
            in_response_to: self._fields.2,
            nsfw: self._fields.3,
            tags: self._fields.4,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Oekaki<S> {
        Oekaki {
            created_at: self._fields.0.unwrap(),
            image: self._fields.1.unwrap(),
            in_response_to: self._fields.2,
            nsfw: self._fields.3,
            tags: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}