// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.sensorthings.observationBatch
//
// 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::{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, open_union};
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::dev_sensorthings::observation_batch;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct BatchEntry<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub q: Option<BatchEntryQ<'a>>,
    ///Observation result, same union as dev.sensorthings.observation
    #[serde(borrow)]
    pub result: BatchEntryResult<'a>,
    ///phenomenonTime
    pub t: Datetime,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum BatchEntryQ<'a> {
    Good,
    Suspect,
    Missing,
    Other(CowStr<'a>),
}

impl<'a> BatchEntryQ<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Good => "dev.sensorthings.quality#good",
            Self::Suspect => "dev.sensorthings.quality#suspect",
            Self::Missing => "dev.sensorthings.quality#missing",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for BatchEntryQ<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "dev.sensorthings.quality#good" => Self::Good,
            "dev.sensorthings.quality#suspect" => Self::Suspect,
            "dev.sensorthings.quality#missing" => Self::Missing,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for BatchEntryQ<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "dev.sensorthings.quality#good" => Self::Good,
            "dev.sensorthings.quality#suspect" => Self::Suspect,
            "dev.sensorthings.quality#missing" => Self::Missing,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> core::fmt::Display for BatchEntryQ<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<'a> AsRef<str> for BatchEntryQ<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> serde::Serialize for BatchEntryQ<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, 'a> serde::Deserialize<'de> for BatchEntryQ<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for BatchEntryQ<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for BatchEntryQ<'_> {
    type Output = BatchEntryQ<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            BatchEntryQ::Good => BatchEntryQ::Good,
            BatchEntryQ::Suspect => BatchEntryQ::Suspect,
            BatchEntryQ::Missing => BatchEntryQ::Missing,
            BatchEntryQ::Other(v) => BatchEntryQ::Other(v.into_static()),
        }
    }
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum BatchEntryResult<'a> {}
/// A batch of observations for a single Datastream, covering a contiguous time window. Trades individual addressability for reduced commit overhead.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ObservationBatch<'a> {
    #[serde(borrow)]
    pub datastream: AtUri<'a>,
    ///Array of observations in chronological order
    #[serde(borrow)]
    pub observations: Vec<observation_batch::BatchEntry<'a>>,
    pub window_end: Datetime,
    pub window_start: Datetime,
}

/// 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 ObservationBatchGetRecordOutput<'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: ObservationBatch<'a>,
}

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

impl<'a> LexiconSchema for BatchEntry<'a> {
    fn nsid() -> &'static str {
        "dev.sensorthings.observationBatch"
    }
    fn def_name() -> &'static str {
        "batchEntry"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_sensorthings_observationBatch()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ObservationBatchRecord;
impl XrpcResp for ObservationBatchRecord {
    const NSID: &'static str = "dev.sensorthings.observationBatch";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ObservationBatchGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for ObservationBatch<'_> {
    const NSID: &'static str = "dev.sensorthings.observationBatch";
    type Record = ObservationBatchRecord;
}

impl Collection for ObservationBatchRecord {
    const NSID: &'static str = "dev.sensorthings.observationBatch";
    type Record = ObservationBatchRecord;
}

impl<'a> LexiconSchema for ObservationBatch<'a> {
    fn nsid() -> &'static str {
        "dev.sensorthings.observationBatch"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_sensorthings_observationBatch()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.observations;
            #[allow(unused_comparisons)]
            if value.len() > 1440usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("observations"),
                    max: 1440usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

pub mod batch_entry_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 Result;
        type T;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Result = Unset;
        type T = Unset;
    }
    ///State transition - sets the `result` field to Set
    pub struct SetResult<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetResult<S> {}
    impl<S: State> State for SetResult<S> {
        type Result = Set<members::result>;
        type T = S::T;
    }
    ///State transition - sets the `t` field to Set
    pub struct SetT<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetT<S> {}
    impl<S: State> State for SetT<S> {
        type Result = S::Result;
        type T = Set<members::t>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `result` field
        pub struct result(());
        ///Marker type for the `t` field
        pub struct t(());
    }
}

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

impl<'a> BatchEntry<'a> {
    /// Create a new builder for this type
    pub fn new() -> BatchEntryBuilder<'a, batch_entry_state::Empty> {
        BatchEntryBuilder::new()
    }
}

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

impl<'a, S: batch_entry_state::State> BatchEntryBuilder<'a, S> {
    /// Set the `q` field (optional)
    pub fn q(mut self, value: impl Into<Option<BatchEntryQ<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `q` field to an Option value (optional)
    pub fn maybe_q(mut self, value: Option<BatchEntryQ<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S> BatchEntryBuilder<'a, S>
where
    S: batch_entry_state::State,
    S::Result: batch_entry_state::IsUnset,
{
    /// Set the `result` field (required)
    pub fn result(
        mut self,
        value: impl Into<BatchEntryResult<'a>>,
    ) -> BatchEntryBuilder<'a, batch_entry_state::SetResult<S>> {
        self._fields.1 = Option::Some(value.into());
        BatchEntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> BatchEntryBuilder<'a, S>
where
    S: batch_entry_state::State,
    S::T: batch_entry_state::IsUnset,
{
    /// Set the `t` field (required)
    pub fn t(
        mut self,
        value: impl Into<Datetime>,
    ) -> BatchEntryBuilder<'a, batch_entry_state::SetT<S>> {
        self._fields.2 = Option::Some(value.into());
        BatchEntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> BatchEntryBuilder<'a, S>
where
    S: batch_entry_state::State,
    S::Result: batch_entry_state::IsSet,
    S::T: batch_entry_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> BatchEntry<'a> {
        BatchEntry {
            q: self._fields.0,
            result: self._fields.1.unwrap(),
            t: self._fields.2.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, Data<'a>>,
    ) -> BatchEntry<'a> {
        BatchEntry {
            q: self._fields.0,
            result: self._fields.1.unwrap(),
            t: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_sensorthings_observationBatch() -> 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("dev.sensorthings.observationBatch"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("batchEntry"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("t"), SmolStr::new_static("result")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("q"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("result"),
                            LexObjectProperty::Union(LexRefUnion {
                                description: Some(
                                    CowStr::new_static(
                                        "Observation result, same union as dev.sensorthings.observation",
                                    ),
                                ),
                                refs: vec![
                                    CowStr::new_static("dev.sensorthings.observation#numericResult"),
                                    CowStr::new_static("dev.sensorthings.observation#categoryResult"),
                                    CowStr::new_static("dev.sensorthings.observation#booleanResult"),
                                    CowStr::new_static("dev.sensorthings.observation#arrayResult"),
                                    CowStr::new_static("dev.sensorthings.observation#geoPointResult")
                                ],
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("t"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("phenomenonTime")),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A batch of observations for a single Datastream, covering a contiguous time window. Trades individual addressability for reduced commit overhead.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("datastream"),
                                SmolStr::new_static("windowStart"),
                                SmolStr::new_static("windowEnd"),
                                SmolStr::new_static("observations")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("datastream"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("observations"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Array of observations in chronological order",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#batchEntry"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(1440usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("windowEnd"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("windowStart"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod observation_batch_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 Observations;
        type WindowStart;
        type WindowEnd;
        type Datastream;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Observations = Unset;
        type WindowStart = Unset;
        type WindowEnd = Unset;
        type Datastream = Unset;
    }
    ///State transition - sets the `observations` field to Set
    pub struct SetObservations<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetObservations<S> {}
    impl<S: State> State for SetObservations<S> {
        type Observations = Set<members::observations>;
        type WindowStart = S::WindowStart;
        type WindowEnd = S::WindowEnd;
        type Datastream = S::Datastream;
    }
    ///State transition - sets the `window_start` field to Set
    pub struct SetWindowStart<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetWindowStart<S> {}
    impl<S: State> State for SetWindowStart<S> {
        type Observations = S::Observations;
        type WindowStart = Set<members::window_start>;
        type WindowEnd = S::WindowEnd;
        type Datastream = S::Datastream;
    }
    ///State transition - sets the `window_end` field to Set
    pub struct SetWindowEnd<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetWindowEnd<S> {}
    impl<S: State> State for SetWindowEnd<S> {
        type Observations = S::Observations;
        type WindowStart = S::WindowStart;
        type WindowEnd = Set<members::window_end>;
        type Datastream = S::Datastream;
    }
    ///State transition - sets the `datastream` field to Set
    pub struct SetDatastream<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDatastream<S> {}
    impl<S: State> State for SetDatastream<S> {
        type Observations = S::Observations;
        type WindowStart = S::WindowStart;
        type WindowEnd = S::WindowEnd;
        type Datastream = Set<members::datastream>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `observations` field
        pub struct observations(());
        ///Marker type for the `window_start` field
        pub struct window_start(());
        ///Marker type for the `window_end` field
        pub struct window_end(());
        ///Marker type for the `datastream` field
        pub struct datastream(());
    }
}

/// Builder for constructing an instance of this type
pub struct ObservationBatchBuilder<'a, S: observation_batch_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<AtUri<'a>>,
        Option<Vec<observation_batch::BatchEntry<'a>>>,
        Option<Datetime>,
        Option<Datetime>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> ObservationBatch<'a> {
    /// Create a new builder for this type
    pub fn new() -> ObservationBatchBuilder<'a, observation_batch_state::Empty> {
        ObservationBatchBuilder::new()
    }
}

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

impl<'a, S> ObservationBatchBuilder<'a, S>
where
    S: observation_batch_state::State,
    S::Datastream: observation_batch_state::IsUnset,
{
    /// Set the `datastream` field (required)
    pub fn datastream(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> ObservationBatchBuilder<'a, observation_batch_state::SetDatastream<S>> {
        self._fields.0 = Option::Some(value.into());
        ObservationBatchBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObservationBatchBuilder<'a, S>
where
    S: observation_batch_state::State,
    S::Observations: observation_batch_state::IsUnset,
{
    /// Set the `observations` field (required)
    pub fn observations(
        mut self,
        value: impl Into<Vec<observation_batch::BatchEntry<'a>>>,
    ) -> ObservationBatchBuilder<'a, observation_batch_state::SetObservations<S>> {
        self._fields.1 = Option::Some(value.into());
        ObservationBatchBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObservationBatchBuilder<'a, S>
where
    S: observation_batch_state::State,
    S::WindowEnd: observation_batch_state::IsUnset,
{
    /// Set the `windowEnd` field (required)
    pub fn window_end(
        mut self,
        value: impl Into<Datetime>,
    ) -> ObservationBatchBuilder<'a, observation_batch_state::SetWindowEnd<S>> {
        self._fields.2 = Option::Some(value.into());
        ObservationBatchBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObservationBatchBuilder<'a, S>
where
    S: observation_batch_state::State,
    S::WindowStart: observation_batch_state::IsUnset,
{
    /// Set the `windowStart` field (required)
    pub fn window_start(
        mut self,
        value: impl Into<Datetime>,
    ) -> ObservationBatchBuilder<'a, observation_batch_state::SetWindowStart<S>> {
        self._fields.3 = Option::Some(value.into());
        ObservationBatchBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ObservationBatchBuilder<'a, S>
where
    S: observation_batch_state::State,
    S::Observations: observation_batch_state::IsSet,
    S::WindowStart: observation_batch_state::IsSet,
    S::WindowEnd: observation_batch_state::IsSet,
    S::Datastream: observation_batch_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ObservationBatch<'a> {
        ObservationBatch {
            datastream: self._fields.0.unwrap(),
            observations: self._fields.1.unwrap(),
            window_end: self._fields.2.unwrap(),
            window_start: self._fields.3.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, Data<'a>>,
    ) -> ObservationBatch<'a> {
        ObservationBatch {
            datastream: self._fields.0.unwrap(),
            observations: self._fields.1.unwrap(),
            window_end: self._fields.2.unwrap(),
            window_start: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}