// @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, 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::{AtUri, Cid, Datetime};
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::sh_tangled::label::op;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "sh.tangled.label.op",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Op<S: BosStr = DefaultStr> {
    pub add: Vec<op::Operand<S>>,
    pub delete: Vec<op::Operand<S>>,
    pub performed_at: Datetime,
    ///The subject (task, pull or discussion) of this label. Appviews may apply a `scope` check and refuse this op.
    pub subject: AtUri<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 OpGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Op<S>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Operand<S: BosStr = DefaultStr> {
    ///ATURI to the label definition
    pub key: AtUri<S>,
    ///Stringified value of the label. This is first unstringed by appviews and then interpreted as a concrete value.
    pub value: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

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

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

impl<S: BosStr> Collection for Op<S> {
    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<S: BosStr> LexiconSchema for Op<S> {
    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<S: BosStr> LexiconSchema for Operand<S> {
    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 Delete;
        type PerformedAt;
        type Subject;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Add = Unset;
        type Delete = Unset;
        type PerformedAt = Unset;
        type Subject = Unset;
    }
    ///State transition - sets the `add` field to Set
    pub struct SetAdd<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetAdd<St> {}
    impl<St: State> State for SetAdd<St> {
        type Add = Set<members::add>;
        type Delete = St::Delete;
        type PerformedAt = St::PerformedAt;
        type Subject = St::Subject;
    }
    ///State transition - sets the `delete` field to Set
    pub struct SetDelete<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDelete<St> {}
    impl<St: State> State for SetDelete<St> {
        type Add = St::Add;
        type Delete = Set<members::delete>;
        type PerformedAt = St::PerformedAt;
        type Subject = St::Subject;
    }
    ///State transition - sets the `performed_at` field to Set
    pub struct SetPerformedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPerformedAt<St> {}
    impl<St: State> State for SetPerformedAt<St> {
        type Add = St::Add;
        type Delete = St::Delete;
        type PerformedAt = Set<members::performed_at>;
        type Subject = St::Subject;
    }
    ///State transition - sets the `subject` field to Set
    pub struct SetSubject<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSubject<St> {}
    impl<St: State> State for SetSubject<St> {
        type Add = St::Add;
        type Delete = St::Delete;
        type PerformedAt = St::PerformedAt;
        type Subject = Set<members::subject>;
    }
    /// 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 `delete` field
        pub struct delete(());
        ///Marker type for the `performed_at` field
        pub struct performed_at(());
        ///Marker type for the `subject` field
        pub struct subject(());
    }
}

/// Builder for constructing an instance of this type.
pub struct OpBuilder<St: op_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<op::Operand<S>>>,
        Option<Vec<op::Operand<S>>>,
        Option<Datetime>,
        Option<AtUri<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

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

impl<St, S: BosStr> OpBuilder<St, S>
where
    St: op_state::State,
    St::Add: op_state::IsSet,
    St::Delete: op_state::IsSet,
    St::PerformedAt: op_state::IsSet,
    St::Subject: op_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Op<S> {
        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<SmolStr, Data<S>>) -> Op<S> {
        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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetKey<St> {}
    impl<St: State> State for SetKey<St> {
        type Key = Set<members::key>;
        type Value = St::Value;
    }
    ///State transition - sets the `value` field to Set
    pub struct SetValue<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetValue<St> {}
    impl<St: State> State for SetValue<St> {
        type Key = St::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<St: operand_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<AtUri<S>>, Option<S>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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