// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: pub.quizzy.answer
//
// 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::com_atproto::repo::strong_ref::StrongRef;
/// A person's answer to a question

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "pub.quizzy.answer",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Answer<S: BosStr = DefaultStr> {
    ///How certain the person is about this answer
    pub certainty: AnswerCertainty<S>,
    ///Reference to the question being answered
    pub question: StrongRef<S>,
    ///The answer text
    pub text: S,
    ///When this answer was submitted
    pub timestamp: Datetime,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// How certain the person is about this answer

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AnswerCertainty<S: BosStr = DefaultStr> {
    DeadCertain,
    FairlySure,
    EducatedGuess,
    WildGuess,
    Other(S),
}

impl<S: BosStr> AnswerCertainty<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::DeadCertain => "deadCertain",
            Self::FairlySure => "fairlySure",
            Self::EducatedGuess => "educatedGuess",
            Self::WildGuess => "wildGuess",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "deadCertain" => Self::DeadCertain,
            "fairlySure" => Self::FairlySure,
            "educatedGuess" => Self::EducatedGuess,
            "wildGuess" => Self::WildGuess,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for AnswerCertainty<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for AnswerCertainty<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for AnswerCertainty<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for AnswerCertainty<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for AnswerCertainty<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for AnswerCertainty<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = AnswerCertainty<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            AnswerCertainty::DeadCertain => AnswerCertainty::DeadCertain,
            AnswerCertainty::FairlySure => AnswerCertainty::FairlySure,
            AnswerCertainty::EducatedGuess => AnswerCertainty::EducatedGuess,
            AnswerCertainty::WildGuess => AnswerCertainty::WildGuess,
            AnswerCertainty::Other(v) => AnswerCertainty::Other(v.into_static()),
        }
    }
}

/// 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 AnswerGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Answer<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct AnswerRecord;
impl XrpcResp for AnswerRecord {
    const NSID: &'static str = "pub.quizzy.answer";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = AnswerGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Answer<S> {
    const NSID: &'static str = "pub.quizzy.answer";
    type Record = AnswerRecord;
}

impl Collection for AnswerRecord {
    const NSID: &'static str = "pub.quizzy.answer";
    type Record = AnswerRecord;
}

impl<S: BosStr> LexiconSchema for Answer<S> {
    fn nsid() -> &'static str {
        "pub.quizzy.answer"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_pub_quizzy_answer()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.text;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("text"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.text;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 100usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("text"),
                        max: 100usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod answer_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 Certainty;
        type Question;
        type Text;
        type Timestamp;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Certainty = Unset;
        type Question = Unset;
        type Text = Unset;
        type Timestamp = Unset;
    }
    ///State transition - sets the `certainty` field to Set
    pub struct SetCertainty<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCertainty<St> {}
    impl<St: State> State for SetCertainty<St> {
        type Certainty = Set<members::certainty>;
        type Question = St::Question;
        type Text = St::Text;
        type Timestamp = St::Timestamp;
    }
    ///State transition - sets the `question` field to Set
    pub struct SetQuestion<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetQuestion<St> {}
    impl<St: State> State for SetQuestion<St> {
        type Certainty = St::Certainty;
        type Question = Set<members::question>;
        type Text = St::Text;
        type Timestamp = St::Timestamp;
    }
    ///State transition - sets the `text` field to Set
    pub struct SetText<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetText<St> {}
    impl<St: State> State for SetText<St> {
        type Certainty = St::Certainty;
        type Question = St::Question;
        type Text = Set<members::text>;
        type Timestamp = St::Timestamp;
    }
    ///State transition - sets the `timestamp` field to Set
    pub struct SetTimestamp<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTimestamp<St> {}
    impl<St: State> State for SetTimestamp<St> {
        type Certainty = St::Certainty;
        type Question = St::Question;
        type Text = St::Text;
        type Timestamp = Set<members::timestamp>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `certainty` field
        pub struct certainty(());
        ///Marker type for the `question` field
        pub struct question(());
        ///Marker type for the `text` field
        pub struct text(());
        ///Marker type for the `timestamp` field
        pub struct timestamp(());
    }
}

/// Builder for constructing an instance of this type.
pub struct AnswerBuilder<St: answer_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<AnswerCertainty<S>>,
        Option<StrongRef<S>>,
        Option<S>,
        Option<Datetime>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Answer<S> {
    /// Create a new builder for this type
    pub fn builder() -> AnswerBuilder<answer_state::Empty, S> {
        AnswerBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> AnswerBuilder<St, S>
where
    St: answer_state::State,
    St::Certainty: answer_state::IsUnset,
{
    /// Set the `certainty` field (required)
    pub fn certainty(
        mut self,
        value: impl Into<AnswerCertainty<S>>,
    ) -> AnswerBuilder<answer_state::SetCertainty<St>, S> {
        self._fields.0 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> AnswerBuilder<St, S>
where
    St: answer_state::State,
    St::Question: answer_state::IsUnset,
{
    /// Set the `question` field (required)
    pub fn question(
        mut self,
        value: impl Into<StrongRef<S>>,
    ) -> AnswerBuilder<answer_state::SetQuestion<St>, S> {
        self._fields.1 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> AnswerBuilder<St, S>
where
    St: answer_state::State,
    St::Text: answer_state::IsUnset,
{
    /// Set the `text` field (required)
    pub fn text(
        mut self,
        value: impl Into<S>,
    ) -> AnswerBuilder<answer_state::SetText<St>, S> {
        self._fields.2 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> AnswerBuilder<St, S>
where
    St: answer_state::State,
    St::Timestamp: answer_state::IsUnset,
{
    /// Set the `timestamp` field (required)
    pub fn timestamp(
        mut self,
        value: impl Into<Datetime>,
    ) -> AnswerBuilder<answer_state::SetTimestamp<St>, S> {
        self._fields.3 = Option::Some(value.into());
        AnswerBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> AnswerBuilder<St, S>
where
    St: answer_state::State,
    St::Certainty: answer_state::IsSet,
    St::Question: answer_state::IsSet,
    St::Text: answer_state::IsSet,
    St::Timestamp: answer_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Answer<S> {
        Answer {
            certainty: self._fields.0.unwrap(),
            question: self._fields.1.unwrap(),
            text: self._fields.2.unwrap(),
            timestamp: 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>>) -> Answer<S> {
        Answer {
            certainty: self._fields.0.unwrap(),
            question: self._fields.1.unwrap(),
            text: self._fields.2.unwrap(),
            timestamp: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_pub_quizzy_answer() -> 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("pub.quizzy.answer"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A person's answer to a question"),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("question"),
                                SmolStr::new_static("text"),
                                SmolStr::new_static("certainty"),
                                SmolStr::new_static("timestamp")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("certainty"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "How certain the person is about this answer",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("question"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("text"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("The answer text")),
                                    max_length: Some(1000usize),
                                    max_graphemes: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("timestamp"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("When this answer was submitted"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}