// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: io.whiteley.luke.ATlas.pin
//
// 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{Did, 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};
/// A user's geographical pin on the ATlas

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "io.whiteley.luke.ATlas.pin",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Pin<S: BosStr = DefaultStr> {
    pub description: S,
    pub did: Did<S>,
    pub latitude: S,
    pub longitude: S,
    pub placed_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub website: Option<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 PinGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Pin<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct PinRecord;
impl XrpcResp for PinRecord {
    const NSID: &'static str = "io.whiteley.luke.ATlas.pin";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = PinGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Pin<S> {
    const NSID: &'static str = "io.whiteley.luke.ATlas.pin";
    type Record = PinRecord;
}

impl Collection for PinRecord {
    const NSID: &'static str = "io.whiteley.luke.ATlas.pin";
    type Record = PinRecord;
}

impl<S: BosStr> LexiconSchema for Pin<S> {
    fn nsid() -> &'static str {
        "io.whiteley.luke.ATlas.pin"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_io_whiteley_luke_ATlas_pin()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.description;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 256usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 256usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.latitude;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("latitude"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.longitude;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("longitude"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.website {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 256usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("website"),
                    max: 256usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod pin_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 Description;
        type Did;
        type Latitude;
        type Longitude;
        type PlacedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Description = Unset;
        type Did = Unset;
        type Latitude = Unset;
        type Longitude = Unset;
        type PlacedAt = Unset;
    }
    ///State transition - sets the `description` field to Set
    pub struct SetDescription<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDescription<St> {}
    impl<St: State> State for SetDescription<St> {
        type Description = Set<members::description>;
        type Did = St::Did;
        type Latitude = St::Latitude;
        type Longitude = St::Longitude;
        type PlacedAt = St::PlacedAt;
    }
    ///State transition - sets the `did` field to Set
    pub struct SetDid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDid<St> {}
    impl<St: State> State for SetDid<St> {
        type Description = St::Description;
        type Did = Set<members::did>;
        type Latitude = St::Latitude;
        type Longitude = St::Longitude;
        type PlacedAt = St::PlacedAt;
    }
    ///State transition - sets the `latitude` field to Set
    pub struct SetLatitude<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLatitude<St> {}
    impl<St: State> State for SetLatitude<St> {
        type Description = St::Description;
        type Did = St::Did;
        type Latitude = Set<members::latitude>;
        type Longitude = St::Longitude;
        type PlacedAt = St::PlacedAt;
    }
    ///State transition - sets the `longitude` field to Set
    pub struct SetLongitude<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLongitude<St> {}
    impl<St: State> State for SetLongitude<St> {
        type Description = St::Description;
        type Did = St::Did;
        type Latitude = St::Latitude;
        type Longitude = Set<members::longitude>;
        type PlacedAt = St::PlacedAt;
    }
    ///State transition - sets the `placed_at` field to Set
    pub struct SetPlacedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPlacedAt<St> {}
    impl<St: State> State for SetPlacedAt<St> {
        type Description = St::Description;
        type Did = St::Did;
        type Latitude = St::Latitude;
        type Longitude = St::Longitude;
        type PlacedAt = Set<members::placed_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `description` field
        pub struct description(());
        ///Marker type for the `did` field
        pub struct did(());
        ///Marker type for the `latitude` field
        pub struct latitude(());
        ///Marker type for the `longitude` field
        pub struct longitude(());
        ///Marker type for the `placed_at` field
        pub struct placed_at(());
    }
}

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

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

impl<S: BosStr> Pin<S> {
    /// Create a new builder for this type
    pub fn builder() -> PinBuilder<pin_state::Empty, S> {
        PinBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> PinBuilder<St, S>
where
    St: pin_state::State,
    St::Description: pin_state::IsUnset,
{
    /// Set the `description` field (required)
    pub fn description(
        mut self,
        value: impl Into<S>,
    ) -> PinBuilder<pin_state::SetDescription<St>, S> {
        self._fields.0 = Option::Some(value.into());
        PinBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> PinBuilder<St, S>
where
    St: pin_state::State,
    St::Did: pin_state::IsUnset,
{
    /// Set the `did` field (required)
    pub fn did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> PinBuilder<pin_state::SetDid<St>, S> {
        self._fields.1 = Option::Some(value.into());
        PinBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> PinBuilder<St, S>
where
    St: pin_state::State,
    St::Latitude: pin_state::IsUnset,
{
    /// Set the `latitude` field (required)
    pub fn latitude(
        mut self,
        value: impl Into<S>,
    ) -> PinBuilder<pin_state::SetLatitude<St>, S> {
        self._fields.2 = Option::Some(value.into());
        PinBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> PinBuilder<St, S>
where
    St: pin_state::State,
    St::Longitude: pin_state::IsUnset,
{
    /// Set the `longitude` field (required)
    pub fn longitude(
        mut self,
        value: impl Into<S>,
    ) -> PinBuilder<pin_state::SetLongitude<St>, S> {
        self._fields.3 = Option::Some(value.into());
        PinBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> PinBuilder<St, S>
where
    St: pin_state::State,
    St::PlacedAt: pin_state::IsUnset,
{
    /// Set the `placedAt` field (required)
    pub fn placed_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> PinBuilder<pin_state::SetPlacedAt<St>, S> {
        self._fields.4 = Option::Some(value.into());
        PinBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: pin_state::State, S: BosStr> PinBuilder<St, S> {
    /// Set the `website` field (optional)
    pub fn website(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `website` field to an Option value (optional)
    pub fn maybe_website(mut self, value: Option<S>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St, S: BosStr> PinBuilder<St, S>
where
    St: pin_state::State,
    St::Description: pin_state::IsSet,
    St::Did: pin_state::IsSet,
    St::Latitude: pin_state::IsSet,
    St::Longitude: pin_state::IsSet,
    St::PlacedAt: pin_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Pin<S> {
        Pin {
            description: self._fields.0.unwrap(),
            did: self._fields.1.unwrap(),
            latitude: self._fields.2.unwrap(),
            longitude: self._fields.3.unwrap(),
            placed_at: self._fields.4.unwrap(),
            website: self._fields.5,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Pin<S> {
        Pin {
            description: self._fields.0.unwrap(),
            did: self._fields.1.unwrap(),
            latitude: self._fields.2.unwrap(),
            longitude: self._fields.3.unwrap(),
            placed_at: self._fields.4.unwrap(),
            website: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_io_whiteley_luke_ATlas_pin() -> 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("io.whiteley.luke.ATlas.pin"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A user's geographical pin on the ATlas"),
                    ),
                    key: Some(CowStr::new_static("literal:self")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("did"),
                                SmolStr::new_static("longitude"),
                                SmolStr::new_static("latitude"),
                                SmolStr::new_static("description"),
                                SmolStr::new_static("placedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("did"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("latitude"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("longitude"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("placedAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("website"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}