// @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, 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, UriValue};
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};
/// Record indicating a livestream is published and available for replication at a given address. By convention, the record key is streamer::server

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "place.stream.broadcast.origin",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Origin<S: BosStr = DefaultStr> {
    ///did of the broadcaster that operates the server syndicating the livestream
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broadcaster: Option<Did<S>>,
    ///Iroh ticket that can be used to access the livestream from the server
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iroh_ticket: Option<S>,
    ///did of the server that's currently rebroadcasting the livestream
    pub server: Did<S>,
    ///DID of the streamer whose livestream is being published
    pub streamer: Did<S>,
    ///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")]
    pub websocket_url: Option<UriValue<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 OriginGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Origin<S>,
}

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

/// 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<S: BosStr> = OriginGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

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

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

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

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

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

impl<St: origin_state::State, S: BosStr> OriginBuilder<St, S> {
    /// Set the `broadcaster` field (optional)
    pub fn broadcaster(mut self, value: impl Into<Option<Did<S>>>) -> 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<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: origin_state::State, S: BosStr> OriginBuilder<St, S> {
    /// Set the `irohTicket` field (optional)
    pub fn iroh_ticket(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

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

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

impl<St: origin_state::State, S: BosStr> OriginBuilder<St, S> {
    /// Set the `websocketURL` field (optional)
    pub fn websocket_url(mut self, value: impl Into<Option<UriValue<S>>>) -> 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<S>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St, S: BosStr> OriginBuilder<St, S>
where
    St: origin_state::State,
    St::Server: origin_state::IsSet,
    St::Streamer: origin_state::IsSet,
    St::UpdatedAt: origin_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Origin<S> {
        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<SmolStr, Data<S>>) -> Origin<S> {
        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()
    }
}