// @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, BosStr, DefaultStr, FromStaticStr};
use jacquard_common::deps::bytes::Bytes;

#[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::{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};
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/.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "io.sound.sequence",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Sequence<S: BosStr = DefaultStr> {
    ///Strong reference to a Bluesky post. Useful to keep track of comments off-platform.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bsky_post_ref: Option<StrongRef<S>>,
    ///Attribution for composers, arrangers, etc
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credits: Option<Vec<Credit<S>>>,
    ///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")]
    pub name: Option<S>,
    ///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")]
    pub sequences: Option<Vec<sequence::Sequence<S>>>,
    ///Array of strings used to tag the sequence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    ///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")]
    pub url: Option<UriValue<S>>,
    ///Version number for the byte array encoding of the events field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<i64>,
    #[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 SequenceGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Sequence<S>,
}

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

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

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

impl<S: BosStr> Collection for Sequence<S> {
    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<S: BosStr> LexiconSchema for Sequence<S> {
    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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetEvents<St> {}
    impl<St: State> State for SetEvents<St> {
        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<St: sequence_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<StrongRef<S>>,
        Option<Vec<Credit<S>>>,
        Option<Bytes>,
        Option<i64>,
        Option<S>,
        Option<Datetime>,
        Option<Vec<sequence::Sequence<S>>>,
        Option<Vec<S>>,
        Option<Datetime>,
        Option<UriValue<S>>,
        Option<i64>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

impl<St: sequence_state::State, S: BosStr> SequenceBuilder<St, 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<St: sequence_state::State, S: BosStr> SequenceBuilder<St, S> {
    /// Set the `name` field (optional)
    pub fn name(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `name` field to an Option value (optional)
    pub fn maybe_name(mut self, value: Option<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: sequence_state::State, S: BosStr> SequenceBuilder<St, 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<St: sequence_state::State, S: BosStr> SequenceBuilder<St, S> {
    /// Set the `sequences` field (optional)
    pub fn sequences(
        mut self,
        value: impl Into<Option<Vec<sequence::Sequence<S>>>>,
    ) -> 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<S>>>) -> Self {
        self._fields.6 = value;
        self
    }
}

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

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

impl<St: sequence_state::State, S: BosStr> SequenceBuilder<St, 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<St, S: BosStr> SequenceBuilder<St, S>
where
    St: sequence_state::State,
    St::Events: sequence_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Sequence<S> {
        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<SmolStr, Data<S>>) -> Sequence<S> {
        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()
    }
}