// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.atsui.List
//
// 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::string::{Did, Nsid};
use jacquard_common::types::value::Data;
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::at_inlay::Element;
use crate::at_inlay::Response;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct List<'a> {
    ///DID of the service that implements the query.
    #[serde(borrow)]
    pub did: Did<'a>,
    ///Parameters to pass to the query.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub input: Option<Data<'a>>,
    ///XRPC query to call for pages of items.
    #[serde(borrow)]
    pub query: Nsid<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ListOutput<'a> {
    #[serde(flatten)]
    #[serde(borrow)]
    pub value: Response<'a>,
}

/// Response shape from a List data source query.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Page<'a> {
    ///Opaque pagination token. Absent means no more items.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cursor: Option<CowStr<'a>>,
    ///Elements to render as list rows.
    #[serde(borrow)]
    pub items: Vec<Element<'a>>,
}

/// Response type for org.atsui.List
pub struct ListResponse;
impl jacquard_common::xrpc::XrpcResp for ListResponse {
    const NSID: &'static str = "org.atsui.List";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ListOutput<'de>;
    type Err<'de> = jacquard_common::xrpc::GenericError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for List<'a> {
    const NSID: &'static str = "org.atsui.List";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = ListResponse;
}

/// Endpoint type for org.atsui.List
pub struct ListRequest;
impl jacquard_common::xrpc::XrpcEndpoint for ListRequest {
    const PATH: &'static str = "/xrpc/org.atsui.List";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<'de> = List<'de>;
    type Response = ListResponse;
}

impl<'a> LexiconSchema for Page<'a> {
    fn nsid() -> &'static str {
        "org.atsui.List"
    }
    fn def_name() -> &'static str {
        "page"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_atsui_List()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.cursor {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("cursor"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

/// Builder for constructing an instance of this type
pub struct ListBuilder<'a, S: list_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Did<'a>>, Option<Data<'a>>, Option<Nsid<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> List<'a> {
    /// Create a new builder for this type
    pub fn new() -> ListBuilder<'a, list_state::Empty> {
        ListBuilder::new()
    }
}

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

impl<'a, S> ListBuilder<'a, S>
where
    S: list_state::State,
    S::Did: list_state::IsUnset,
{
    /// Set the `did` field (required)
    pub fn did(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> ListBuilder<'a, list_state::SetDid<S>> {
        self._fields.0 = Option::Some(value.into());
        ListBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: list_state::State> ListBuilder<'a, S> {
    /// Set the `input` field (optional)
    pub fn input(mut self, value: impl Into<Option<Data<'a>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `input` field to an Option value (optional)
    pub fn maybe_input(mut self, value: Option<Data<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S> ListBuilder<'a, S>
where
    S: list_state::State,
    S::Query: list_state::IsUnset,
{
    /// Set the `query` field (required)
    pub fn query(
        mut self,
        value: impl Into<Nsid<'a>>,
    ) -> ListBuilder<'a, list_state::SetQuery<S>> {
        self._fields.2 = Option::Some(value.into());
        ListBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ListBuilder<'a, S>
where
    S: list_state::State,
    S::Query: list_state::IsSet,
    S::Did: list_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> List<'a> {
        List {
            did: self._fields.0.unwrap(),
            input: self._fields.1,
            query: 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>>,
    ) -> List<'a> {
        List {
            did: self._fields.0.unwrap(),
            input: self._fields.1,
            query: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

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

/// Builder for constructing an instance of this type
pub struct PageBuilder<'a, S: page_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<Vec<Element<'a>>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Page<'a> {
    /// Create a new builder for this type
    pub fn new() -> PageBuilder<'a, page_state::Empty> {
        PageBuilder::new()
    }
}

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

impl<'a, S: page_state::State> PageBuilder<'a, S> {
    /// Set the `cursor` field (optional)
    pub fn cursor(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `cursor` field to an Option value (optional)
    pub fn maybe_cursor(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S> PageBuilder<'a, S>
where
    S: page_state::State,
    S::Items: page_state::IsUnset,
{
    /// Set the `items` field (required)
    pub fn items(
        mut self,
        value: impl Into<Vec<Element<'a>>>,
    ) -> PageBuilder<'a, page_state::SetItems<S>> {
        self._fields.1 = Option::Some(value.into());
        PageBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> PageBuilder<'a, S>
where
    S: page_state::State,
    S::Items: page_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Page<'a> {
        Page {
            cursor: self._fields.0,
            items: self._fields.1.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>>,
    ) -> Page<'a> {
        Page {
            cursor: self._fields.0,
            items: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_atsui_List() -> 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("org.atsui.List"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcProcedure(LexXrpcProcedure {
                    input: Some(LexXrpcBody {
                        encoding: CowStr::new_static("application/json"),
                        schema: Some(
                            LexXrpcBodySchema::Object(LexObject {
                                required: Some(
                                    vec![
                                        SmolStr::new_static("query"), SmolStr::new_static("did")
                                    ],
                                ),
                                properties: {
                                    #[allow(unused_mut)]
                                    let mut map = BTreeMap::new();
                                    map.insert(
                                        SmolStr::new_static("did"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static(
                                                    "DID of the service that implements the query.",
                                                ),
                                            ),
                                            format: Some(LexStringFormat::Did),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("input"),
                                        LexObjectProperty::Unknown(LexUnknown {
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("query"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static("XRPC query to call for pages of items."),
                                            ),
                                            format: Some(LexStringFormat::Nsid),
                                            ..Default::default()
                                        }),
                                    );
                                    map
                                },
                                ..Default::default()
                            }),
                        ),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("page"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Response shape from a List data source query.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("items")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("cursor"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Opaque pagination token. Absent means no more items.",
                                    ),
                                ),
                                max_length: Some(512usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("items"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static("Elements to render as list rows."),
                                ),
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("at.inlay.defs#element"),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}