// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: blue.atroom.room.object
//
// 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::blue_atroom::room::object;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct LocalizedName<S: BosStr = DefaultStr> {
    pub lang: S,
    pub value: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A 3D object that can be placed in a room.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "blue.atroom.room.object",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Object<S: BosStr = DefaultStr> {
    pub created_at: Datetime,
    pub model: BlobRef<S>,
    pub name: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_langs: Option<Vec<object::LocalizedName<S>>>,
    pub scale: i64,
    #[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 ObjectGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Object<S>,
}

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

impl<S: BosStr> LexiconSchema for LocalizedName<S> {
    fn nsid() -> &'static str {
        "blue.atroom.room.object"
    }
    fn def_name() -> &'static str {
        "localizedName"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_blue_atroom_room_object()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.lang;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 16usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("lang"),
                    max: 16usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.value;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("value"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ObjectRecord;
impl XrpcResp for ObjectRecord {
    const NSID: &'static str = "blue.atroom.room.object";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = ObjectGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Object<S> {
    const NSID: &'static str = "blue.atroom.room.object";
    type Record = ObjectRecord;
}

impl Collection for ObjectRecord {
    const NSID: &'static str = "blue.atroom.room.object";
    type Record = ObjectRecord;
}

impl<S: BosStr> LexiconSchema for Object<S> {
    fn nsid() -> &'static str {
        "blue.atroom.room.object"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_blue_atroom_room_object()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.model;
            {
                let size = value.blob().size;
                if size > 10485760usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("model"),
                        max: 10485760usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.model;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["model/gltf-binary"];
                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("model"),
                        accepted: vec!["model/gltf-binary".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.scale;
            if *value > 1000i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("scale"),
                    max: 1000i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.scale;
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("scale"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

fn lexicon_doc_blue_atroom_room_object() -> 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("blue.atroom.room.object"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("localizedName"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("lang"), SmolStr::new_static("value")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("lang"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(16usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(100usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A 3D object that can be placed in a room."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("name"), SmolStr::new_static("model"),
                                SmolStr::new_static("scale"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("model"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("nameLangs"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#localizedName"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("scale"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(1i64),
                                    maximum: Some(1000i64),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod object_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 Model;
        type Name;
        type Scale;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Model = Unset;
        type Name = Unset;
        type Scale = 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 Model = St::Model;
        type Name = St::Name;
        type Scale = St::Scale;
    }
    ///State transition - sets the `model` field to Set
    pub struct SetModel<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetModel<St> {}
    impl<St: State> State for SetModel<St> {
        type CreatedAt = St::CreatedAt;
        type Model = Set<members::model>;
        type Name = St::Name;
        type Scale = St::Scale;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type CreatedAt = St::CreatedAt;
        type Model = St::Model;
        type Name = Set<members::name>;
        type Scale = St::Scale;
    }
    ///State transition - sets the `scale` field to Set
    pub struct SetScale<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetScale<St> {}
    impl<St: State> State for SetScale<St> {
        type CreatedAt = St::CreatedAt;
        type Model = St::Model;
        type Name = St::Name;
        type Scale = Set<members::scale>;
    }
    /// 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 `model` field
        pub struct model(());
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `scale` field
        pub struct scale(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ObjectBuilder<St: object_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<BlobRef<S>>,
        Option<S>,
        Option<Vec<object::LocalizedName<S>>>,
        Option<i64>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Object<S> {
    /// Create a new builder for this type
    pub fn builder() -> ObjectBuilder<object_state::Empty, S> {
        ObjectBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> ObjectBuilder<St, S>
where
    St: object_state::State,
    St::Model: object_state::IsUnset,
{
    /// Set the `model` field (required)
    pub fn model(
        mut self,
        value: impl Into<BlobRef<S>>,
    ) -> ObjectBuilder<object_state::SetModel<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ObjectBuilder<St, S>
where
    St: object_state::State,
    St::Name: object_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<S>,
    ) -> ObjectBuilder<object_state::SetName<St>, S> {
        self._fields.2 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: object_state::State, S: BosStr> ObjectBuilder<St, S> {
    /// Set the `nameLangs` field (optional)
    pub fn name_langs(
        mut self,
        value: impl Into<Option<Vec<object::LocalizedName<S>>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `nameLangs` field to an Option value (optional)
    pub fn maybe_name_langs(
        mut self,
        value: Option<Vec<object::LocalizedName<S>>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> ObjectBuilder<St, S>
where
    St: object_state::State,
    St::Scale: object_state::IsUnset,
{
    /// Set the `scale` field (required)
    pub fn scale(
        mut self,
        value: impl Into<i64>,
    ) -> ObjectBuilder<object_state::SetScale<St>, S> {
        self._fields.4 = Option::Some(value.into());
        ObjectBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ObjectBuilder<St, S>
where
    St: object_state::State,
    St::CreatedAt: object_state::IsSet,
    St::Model: object_state::IsSet,
    St::Name: object_state::IsSet,
    St::Scale: object_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Object<S> {
        Object {
            created_at: self._fields.0.unwrap(),
            model: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            name_langs: self._fields.3,
            scale: self._fields.4.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>>) -> Object<S> {
        Object {
            created_at: self._fields.0.unwrap(),
            model: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            name_langs: self._fields.3,
            scale: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}