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

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Pin<'a> {
    #[serde(borrow)]
    pub description: CowStr<'a>,
    #[serde(borrow)]
    pub did: Did<'a>,
    #[serde(borrow)]
    pub latitude: CowStr<'a>,
    #[serde(borrow)]
    pub longitude: CowStr<'a>,
    pub placed_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub website: Option<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 PinGetRecordOutput<'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: Pin<'a>,
}

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

/// 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<'de> = PinGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

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

/// Builder for constructing an instance of this type
pub struct PinBuilder<'a, S: pin_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<Did<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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

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

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

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

impl<'a, S> PinBuilder<'a, S>
where
    S: pin_state::State,
    S::Did: pin_state::IsSet,
    S::Longitude: pin_state::IsSet,
    S::PlacedAt: pin_state::IsSet,
    S::Description: pin_state::IsSet,
    S::Latitude: pin_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Pin<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Pin<'a> {
        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()
    }
}