// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: sh.tangled.label.op
//
// 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::{AtUri, Cid, Datetime};
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::sh_tangled::label::op;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Op<'a> {
    #[serde(borrow)]
    pub add: Vec<op::Operand<'a>>,
    #[serde(borrow)]
    pub delete: Vec<op::Operand<'a>>,
    pub performed_at: Datetime,
    ///The subject (task, pull or discussion) of this label. Appviews may apply a `scope` check and refuse this op.
    #[serde(borrow)]
    pub subject: AtUri<'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 OpGetRecordOutput<'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: Op<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Operand<'a> {
    ///ATURI to the label definition
    #[serde(borrow)]
    pub key: AtUri<'a>,
    ///Stringified value of the label. This is first unstringed by appviews and then interpreted as a concrete value.
    #[serde(borrow)]
    pub value: CowStr<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct OpRecord;
impl XrpcResp for OpRecord {
    const NSID: &'static str = "sh.tangled.label.op";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = OpGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Op<'_> {
    const NSID: &'static str = "sh.tangled.label.op";
    type Record = OpRecord;
}

impl Collection for OpRecord {
    const NSID: &'static str = "sh.tangled.label.op";
    type Record = OpRecord;
}

impl<'a> LexiconSchema for Op<'a> {
    fn nsid() -> &'static str {
        "sh.tangled.label.op"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_tangled_label_op()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<'a> LexiconSchema for Operand<'a> {
    fn nsid() -> &'static str {
        "sh.tangled.label.op"
    }
    fn def_name() -> &'static str {
        "operand"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_tangled_label_op()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

pub mod op_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 Add;
        type PerformedAt;
        type Subject;
        type Delete;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Add = Unset;
        type PerformedAt = Unset;
        type Subject = Unset;
        type Delete = Unset;
    }
    ///State transition - sets the `add` field to Set
    pub struct SetAdd<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAdd<S> {}
    impl<S: State> State for SetAdd<S> {
        type Add = Set<members::add>;
        type PerformedAt = S::PerformedAt;
        type Subject = S::Subject;
        type Delete = S::Delete;
    }
    ///State transition - sets the `performed_at` field to Set
    pub struct SetPerformedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPerformedAt<S> {}
    impl<S: State> State for SetPerformedAt<S> {
        type Add = S::Add;
        type PerformedAt = Set<members::performed_at>;
        type Subject = S::Subject;
        type Delete = S::Delete;
    }
    ///State transition - sets the `subject` field to Set
    pub struct SetSubject<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSubject<S> {}
    impl<S: State> State for SetSubject<S> {
        type Add = S::Add;
        type PerformedAt = S::PerformedAt;
        type Subject = Set<members::subject>;
        type Delete = S::Delete;
    }
    ///State transition - sets the `delete` field to Set
    pub struct SetDelete<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDelete<S> {}
    impl<S: State> State for SetDelete<S> {
        type Add = S::Add;
        type PerformedAt = S::PerformedAt;
        type Subject = S::Subject;
        type Delete = Set<members::delete>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `add` field
        pub struct add(());
        ///Marker type for the `performed_at` field
        pub struct performed_at(());
        ///Marker type for the `subject` field
        pub struct subject(());
        ///Marker type for the `delete` field
        pub struct delete(());
    }
}

/// Builder for constructing an instance of this type
pub struct OpBuilder<'a, S: op_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<op::Operand<'a>>>,
        Option<Vec<op::Operand<'a>>>,
        Option<Datetime>,
        Option<AtUri<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Op<'a> {
    /// Create a new builder for this type
    pub fn new() -> OpBuilder<'a, op_state::Empty> {
        OpBuilder::new()
    }
}

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

impl<'a, S> OpBuilder<'a, S>
where
    S: op_state::State,
    S::Add: op_state::IsUnset,
{
    /// Set the `add` field (required)
    pub fn add(
        mut self,
        value: impl Into<Vec<op::Operand<'a>>>,
    ) -> OpBuilder<'a, op_state::SetAdd<S>> {
        self._fields.0 = Option::Some(value.into());
        OpBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OpBuilder<'a, S>
where
    S: op_state::State,
    S::Delete: op_state::IsUnset,
{
    /// Set the `delete` field (required)
    pub fn delete(
        mut self,
        value: impl Into<Vec<op::Operand<'a>>>,
    ) -> OpBuilder<'a, op_state::SetDelete<S>> {
        self._fields.1 = Option::Some(value.into());
        OpBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OpBuilder<'a, S>
where
    S: op_state::State,
    S::PerformedAt: op_state::IsUnset,
{
    /// Set the `performedAt` field (required)
    pub fn performed_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> OpBuilder<'a, op_state::SetPerformedAt<S>> {
        self._fields.2 = Option::Some(value.into());
        OpBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OpBuilder<'a, S>
where
    S: op_state::State,
    S::Subject: op_state::IsUnset,
{
    /// Set the `subject` field (required)
    pub fn subject(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> OpBuilder<'a, op_state::SetSubject<S>> {
        self._fields.3 = Option::Some(value.into());
        OpBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OpBuilder<'a, S>
where
    S: op_state::State,
    S::Add: op_state::IsSet,
    S::PerformedAt: op_state::IsSet,
    S::Subject: op_state::IsSet,
    S::Delete: op_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Op<'a> {
        Op {
            add: self._fields.0.unwrap(),
            delete: self._fields.1.unwrap(),
            performed_at: self._fields.2.unwrap(),
            subject: self._fields.3.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,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Op<'a> {
        Op {
            add: self._fields.0.unwrap(),
            delete: self._fields.1.unwrap(),
            performed_at: self._fields.2.unwrap(),
            subject: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_sh_tangled_label_op() -> 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("sh.tangled.label.op"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("subject"), SmolStr::new_static("add"),
                                SmolStr::new_static("delete"),
                                SmolStr::new_static("performedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("add"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#operand"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("delete"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#operand"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("performedAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subject"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The subject (task, pull or discussion) of this label. Appviews may apply a `scope` check and refuse this op.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("operand"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("key"), SmolStr::new_static("value")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("key"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("ATURI to the label definition"),
                                ),
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Stringified value of the label. This is first unstringed by appviews and then interpreted as a concrete value.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

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

impl<'a> Operand<'a> {
    /// Create a new builder for this type
    pub fn new() -> OperandBuilder<'a, operand_state::Empty> {
        OperandBuilder::new()
    }
}

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

impl<'a, S> OperandBuilder<'a, S>
where
    S: operand_state::State,
    S::Key: operand_state::IsUnset,
{
    /// Set the `key` field (required)
    pub fn key(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> OperandBuilder<'a, operand_state::SetKey<S>> {
        self._fields.0 = Option::Some(value.into());
        OperandBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OperandBuilder<'a, S>
where
    S: operand_state::State,
    S::Value: operand_state::IsUnset,
{
    /// Set the `value` field (required)
    pub fn value(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> OperandBuilder<'a, operand_state::SetValue<S>> {
        self._fields.1 = Option::Some(value.into());
        OperandBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> OperandBuilder<'a, S>
where
    S: operand_state::State,
    S::Key: operand_state::IsSet,
    S::Value: operand_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Operand<'a> {
        Operand {
            key: self._fields.0.unwrap(),
            value: 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,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Operand<'a> {
        Operand {
            key: self._fields.0.unwrap(),
            value: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}