// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: place.stream.broadcast.origin
//
// 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, UriValue};
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};
/// Record indicating a livestream is published and available for replication at a given address. By convention, the record key is streamer::server

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Origin<'a> {
    ///did of the broadcaster that operates the server syndicating the livestream
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub broadcaster: Option<Did<'a>>,
    ///Iroh ticket that can be used to access the livestream from the server
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub iroh_ticket: Option<CowStr<'a>>,
    ///did of the server that's currently rebroadcasting the livestream
    #[serde(borrow)]
    pub server: Did<'a>,
    ///DID of the streamer whose livestream is being published
    #[serde(borrow)]
    pub streamer: Did<'a>,
    ///Periodically updated timestamp when this origin last saw a livestream
    pub updated_at: Datetime,
    ///URL of the websocket endpoint for the livestream
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub websocket_url: Option<UriValue<'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 OriginGetRecordOutput<'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: Origin<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct OriginRecord;
impl XrpcResp for OriginRecord {
    const NSID: &'static str = "place.stream.broadcast.origin";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = OriginGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Origin<'_> {
    const NSID: &'static str = "place.stream.broadcast.origin";
    type Record = OriginRecord;
}

impl Collection for OriginRecord {
    const NSID: &'static str = "place.stream.broadcast.origin";
    type Record = OriginRecord;
}

impl<'a> LexiconSchema for Origin<'a> {
    fn nsid() -> &'static str {
        "place.stream.broadcast.origin"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_place_stream_broadcast_origin()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.iroh_ticket {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2048usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("iroh_ticket"),
                    max: 2048usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod origin_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 Streamer;
        type UpdatedAt;
        type Server;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Streamer = Unset;
        type UpdatedAt = Unset;
        type Server = Unset;
    }
    ///State transition - sets the `streamer` field to Set
    pub struct SetStreamer<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetStreamer<S> {}
    impl<S: State> State for SetStreamer<S> {
        type Streamer = Set<members::streamer>;
        type UpdatedAt = S::UpdatedAt;
        type Server = S::Server;
    }
    ///State transition - sets the `updated_at` field to Set
    pub struct SetUpdatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUpdatedAt<S> {}
    impl<S: State> State for SetUpdatedAt<S> {
        type Streamer = S::Streamer;
        type UpdatedAt = Set<members::updated_at>;
        type Server = S::Server;
    }
    ///State transition - sets the `server` field to Set
    pub struct SetServer<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetServer<S> {}
    impl<S: State> State for SetServer<S> {
        type Streamer = S::Streamer;
        type UpdatedAt = S::UpdatedAt;
        type Server = Set<members::server>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `streamer` field
        pub struct streamer(());
        ///Marker type for the `updated_at` field
        pub struct updated_at(());
        ///Marker type for the `server` field
        pub struct server(());
    }
}

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

impl<'a> Origin<'a> {
    /// Create a new builder for this type
    pub fn new() -> OriginBuilder<'a, origin_state::Empty> {
        OriginBuilder::new()
    }
}

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

impl<'a, S: origin_state::State> OriginBuilder<'a, S> {
    /// Set the `broadcaster` field (optional)
    pub fn broadcaster(mut self, value: impl Into<Option<Did<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `broadcaster` field to an Option value (optional)
    pub fn maybe_broadcaster(mut self, value: Option<Did<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S: origin_state::State> OriginBuilder<'a, S> {
    /// Set the `irohTicket` field (optional)
    pub fn iroh_ticket(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `irohTicket` field to an Option value (optional)
    pub fn maybe_iroh_ticket(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S> OriginBuilder<'a, S>
where
    S: origin_state::State,
    S::Server: origin_state::IsUnset,
{
    /// Set the `server` field (required)
    pub fn server(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> OriginBuilder<'a, origin_state::SetServer<S>> {
        self._fields.2 = Option::Some(value.into());
        OriginBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OriginBuilder<'a, S>
where
    S: origin_state::State,
    S::Streamer: origin_state::IsUnset,
{
    /// Set the `streamer` field (required)
    pub fn streamer(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> OriginBuilder<'a, origin_state::SetStreamer<S>> {
        self._fields.3 = Option::Some(value.into());
        OriginBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OriginBuilder<'a, S>
where
    S: origin_state::State,
    S::UpdatedAt: origin_state::IsUnset,
{
    /// Set the `updatedAt` field (required)
    pub fn updated_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> OriginBuilder<'a, origin_state::SetUpdatedAt<S>> {
        self._fields.4 = Option::Some(value.into());
        OriginBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: origin_state::State> OriginBuilder<'a, S> {
    /// Set the `websocketURL` field (optional)
    pub fn websocket_url(mut self, value: impl Into<Option<UriValue<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `websocketURL` field to an Option value (optional)
    pub fn maybe_websocket_url(mut self, value: Option<UriValue<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> OriginBuilder<'a, S>
where
    S: origin_state::State,
    S::Streamer: origin_state::IsSet,
    S::UpdatedAt: origin_state::IsSet,
    S::Server: origin_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Origin<'a> {
        Origin {
            broadcaster: self._fields.0,
            iroh_ticket: self._fields.1,
            server: self._fields.2.unwrap(),
            streamer: self._fields.3.unwrap(),
            updated_at: self._fields.4.unwrap(),
            websocket_url: 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>,
        >,
    ) -> Origin<'a> {
        Origin {
            broadcaster: self._fields.0,
            iroh_ticket: self._fields.1,
            server: self._fields.2.unwrap(),
            streamer: self._fields.3.unwrap(),
            updated_at: self._fields.4.unwrap(),
            websocket_url: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_place_stream_broadcast_origin() -> 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("place.stream.broadcast.origin"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Record indicating a livestream is published and available for replication at a given address. By convention, the record key is streamer::server",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("streamer"),
                                SmolStr::new_static("server"),
                                SmolStr::new_static("updatedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("broadcaster"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "did of the broadcaster that operates the server syndicating the livestream",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("irohTicket"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Iroh ticket that can be used to access the livestream from the server",
                                        ),
                                    ),
                                    max_length: Some(2048usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("server"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "did of the server that's currently rebroadcasting the livestream",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("streamer"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "DID of the streamer whose livestream is being published",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Periodically updated timestamp when this origin last saw a livestream",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("websocketURL"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "URL of the websocket endpoint for the livestream",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}