// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: io.sound.sequence
//
// 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;
use jacquard_common::deps::bytes::Bytes;

#[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, 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};
use crate::com_atproto::repo::strong_ref::StrongRef;
use crate::io_sound::credit::Credit;
use crate::io_sound::sequence;
/// A sequence of timed events. Full documentation at https://github.com/soundio/sequence/.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Sequence<'a> {
    ///Strong reference to a Bluesky post. Useful to keep track of comments off-platform.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub bsky_post_ref: Option<StrongRef<'a>>,
    ///Attribution for composers, arrangers, etc
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub credits: Option<Vec<Credit<'a>>>,
    ///Serialised and binary encoded array of events of the form `[beat, type, data...]`, where `data` parameters depend on `type` and the byte layout of the serialised data conforms to the Sequence spec at https://github.com/soundio/sequence.
    #[serde(with = "jacquard_common::serde_bytes_helper")]
    pub events: Bytes,
    ///Identifies this sequence for playback by a "sequence" event.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i64>,
    ///Name of the sequence
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub name: Option<CowStr<'a>>,
    ///Timestamp of the time of publication.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published_at: Option<Datetime>,
    ///A collection of sequences that may be played back by "sequence" events.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub sequences: Option<Vec<sequence::Sequence<'a>>>,
    ///Array of strings used to tag the sequence.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
    ///Timestamp of the time of last edit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Datetime>,
    ///Canonical location of this sequence. May be an `at://` URI or an `https://` URL to a JSON endpoint.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub url: Option<UriValue<'a>>,
    ///Version number for the byte array encoding of the events field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<i64>,
}

/// 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 SequenceGetRecordOutput<'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: Sequence<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct SequenceRecord;
impl XrpcResp for SequenceRecord {
    const NSID: &'static str = "io.sound.sequence";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = SequenceGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Sequence<'_> {
    const NSID: &'static str = "io.sound.sequence";
    type Record = SequenceRecord;
}

impl Collection for SequenceRecord {
    const NSID: &'static str = "io.sound.sequence";
    type Record = SequenceRecord;
}

impl<'a> LexiconSchema for Sequence<'a> {
    fn nsid() -> &'static str {
        "io.sound.sequence"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_io_sound_sequence()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.credits {
            #[allow(unused_comparisons)]
            if value.len() > 60usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("credits"),
                    max: 60usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.id {
            if *value > 65535i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("id"),
                    max: 65535i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.name {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1280usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 1280usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.name {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 640usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("name"),
                        max: 640usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

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

/// Builder for constructing an instance of this type
pub struct SequenceBuilder<'a, S: sequence_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<StrongRef<'a>>,
        Option<Vec<Credit<'a>>>,
        Option<Bytes>,
        Option<i64>,
        Option<CowStr<'a>>,
        Option<Datetime>,
        Option<Vec<sequence::Sequence<'a>>>,
        Option<Vec<CowStr<'a>>>,
        Option<Datetime>,
        Option<UriValue<'a>>,
        Option<i64>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Sequence<'a> {
    /// Create a new builder for this type
    pub fn new() -> SequenceBuilder<'a, sequence_state::Empty> {
        SequenceBuilder::new()
    }
}

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

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `bskyPostRef` field (optional)
    pub fn bsky_post_ref(mut self, value: impl Into<Option<StrongRef<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `bskyPostRef` field to an Option value (optional)
    pub fn maybe_bsky_post_ref(mut self, value: Option<StrongRef<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `credits` field (optional)
    pub fn credits(mut self, value: impl Into<Option<Vec<Credit<'a>>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `credits` field to an Option value (optional)
    pub fn maybe_credits(mut self, value: Option<Vec<Credit<'a>>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S> SequenceBuilder<'a, S>
where
    S: sequence_state::State,
    S::Events: sequence_state::IsUnset,
{
    /// Set the `events` field (required)
    pub fn events(
        mut self,
        value: impl Into<Bytes>,
    ) -> SequenceBuilder<'a, sequence_state::SetEvents<S>> {
        self._fields.2 = Option::Some(value.into());
        SequenceBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `id` field (optional)
    pub fn id(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `id` field to an Option value (optional)
    pub fn maybe_id(mut self, value: Option<i64>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `name` field (optional)
    pub fn name(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `name` field to an Option value (optional)
    pub fn maybe_name(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `publishedAt` field (optional)
    pub fn published_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `publishedAt` field to an Option value (optional)
    pub fn maybe_published_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `sequences` field (optional)
    pub fn sequences(
        mut self,
        value: impl Into<Option<Vec<sequence::Sequence<'a>>>>,
    ) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `sequences` field to an Option value (optional)
    pub fn maybe_sequences(
        mut self,
        value: Option<Vec<sequence::Sequence<'a>>>,
    ) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `tags` field to an Option value (optional)
    pub fn maybe_tags(mut self, value: Option<Vec<CowStr<'a>>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `updatedAt` field (optional)
    pub fn updated_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `updatedAt` field to an Option value (optional)
    pub fn maybe_updated_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `url` field (optional)
    pub fn url(mut self, value: impl Into<Option<UriValue<'a>>>) -> Self {
        self._fields.9 = value.into();
        self
    }
    /// Set the `url` field to an Option value (optional)
    pub fn maybe_url(mut self, value: Option<UriValue<'a>>) -> Self {
        self._fields.9 = value;
        self
    }
}

impl<'a, S: sequence_state::State> SequenceBuilder<'a, S> {
    /// Set the `version` field (optional)
    pub fn version(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.10 = value.into();
        self
    }
    /// Set the `version` field to an Option value (optional)
    pub fn maybe_version(mut self, value: Option<i64>) -> Self {
        self._fields.10 = value;
        self
    }
}

impl<'a, S> SequenceBuilder<'a, S>
where
    S: sequence_state::State,
    S::Events: sequence_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Sequence<'a> {
        Sequence {
            bsky_post_ref: self._fields.0,
            credits: self._fields.1,
            events: self._fields.2.unwrap(),
            id: self._fields.3,
            name: self._fields.4,
            published_at: self._fields.5,
            sequences: self._fields.6,
            tags: self._fields.7,
            updated_at: self._fields.8,
            url: self._fields.9,
            version: self._fields.10,
            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>,
        >,
    ) -> Sequence<'a> {
        Sequence {
            bsky_post_ref: self._fields.0,
            credits: self._fields.1,
            events: self._fields.2.unwrap(),
            id: self._fields.3,
            name: self._fields.4,
            published_at: self._fields.5,
            sequences: self._fields.6,
            tags: self._fields.7,
            updated_at: self._fields.8,
            url: self._fields.9,
            version: self._fields.10,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_io_sound_sequence() -> 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.sound.sequence"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A sequence of timed events. Full documentation at https://github.com/soundio/sequence/.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("events")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("bskyPostRef"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("credits"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Attribution for composers, arrangers, etc",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("io.sound.credit"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(60usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("events"),
                                LexObjectProperty::Bytes(LexBytes {
                                    max_length: Some(524288usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("id"),
                                LexObjectProperty::Integer(LexInteger {
                                    maximum: Some(65535i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Name of the sequence"),
                                    ),
                                    max_length: Some(1280usize),
                                    max_graphemes: Some(640usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("publishedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Timestamp of the time of publication."),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("sequences"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "A collection of sequences that may be played back by \"sequence\" events.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("io.sound.sequence"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Array of strings used to tag the sequence.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(1280usize),
                                        max_graphemes: Some(128usize),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Timestamp of the time of last edit."),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("url"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Canonical location of this sequence. May be an `at://` URI or an `https://` URL to a JSON endpoint.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("version"),
                                LexObjectProperty::Integer(LexInteger {
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}