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

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Image<'a> {
    ///The actual atproto image blob.
    #[serde(borrow)]
    pub blob: BlobRef<'a>,
    #[serde(borrow)]
    pub image_link: oekaki::ImageLink<'a>,
}

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct ImageLink<'a> {
    ///Alt text description of the image, for accessibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub alt: Option<CowStr<'a>>,
}

/// An oekaki post.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Oekaki<'a> {
    ///The timestamp of creation.
    pub created_at: Datetime,
    #[serde(borrow)]
    pub image: oekaki::Image<'a>,
    ///What this oekaki post is a response to.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub in_response_to: Option<StrongRef<'a>>,
    ///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")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
}

/// 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<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Oekaki<'a>,
}

impl<'a> Oekaki<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, OekakiRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

impl<'a> LexiconSchema for Image<'a> {
    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<'a> LexiconSchema for ImageLink<'a> {
    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<'de> = OekakiGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<OekakiGetRecordOutput<'_>> for Oekaki<'_> {
    fn from(output: OekakiGetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

impl Collection for Oekaki<'_> {
    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<'a> LexiconSchema for Oekaki<'a> {
    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 ImageLink;
        type Blob;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type ImageLink = Unset;
        type Blob = Unset;
    }
    ///State transition - sets the `image_link` field to Set
    pub struct SetImageLink<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetImageLink<S> {}
    impl<S: State> State for SetImageLink<S> {
        type ImageLink = Set<members::image_link>;
        type Blob = S::Blob;
    }
    ///State transition - sets the `blob` field to Set
    pub struct SetBlob<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetBlob<S> {}
    impl<S: State> State for SetBlob<S> {
        type ImageLink = S::ImageLink;
        type Blob = Set<members::blob>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `image_link` field
        pub struct image_link(());
        ///Marker type for the `blob` field
        pub struct blob(());
    }
}

/// Builder for constructing an instance of this type
pub struct ImageBuilder<'a, S: image_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<BlobRef<'a>>, Option<oekaki::ImageLink<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> ImageBuilder<'a, S>
where
    S: image_state::State,
    S::ImageLink: image_state::IsSet,
    S::Blob: image_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Image<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Image<'a> {
        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 Image;
        type CreatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Image = Unset;
        type CreatedAt = Unset;
    }
    ///State transition - sets the `image` field to Set
    pub struct SetImage<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetImage<S> {}
    impl<S: State> State for SetImage<S> {
        type Image = Set<members::image>;
        type CreatedAt = S::CreatedAt;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type Image = S::Image;
        type CreatedAt = Set<members::created_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `image` field
        pub struct image(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
    }
}

/// Builder for constructing an instance of this type
pub struct OekakiBuilder<'a, S: oekaki_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<oekaki::Image<'a>>,
        Option<StrongRef<'a>>,
        Option<bool>,
        Option<Vec<CowStr<'a>>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S: oekaki_state::State> OekakiBuilder<'a, S> {
    /// Set the `inResponseTo` field (optional)
    pub fn in_response_to(mut self, value: impl Into<Option<StrongRef<'a>>>) -> 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<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: oekaki_state::State> OekakiBuilder<'a, 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<'a, S: oekaki_state::State> OekakiBuilder<'a, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> 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<CowStr<'a>>>) -> Self {
        self._fields.4 = value;
        self
    }
}

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