1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use crate::{
    ArgumentParam,
    BuilderError,
};
use serenity::model::application::{
    CommandDataOptionValue,
    CommandInteraction,
};

/// Error while converting from an interaction
#[derive(Debug, thiserror::Error)]
pub enum ConvertError {
    /// The type is unknown
    #[error("unexpected type for '{name}', expected '{expected}', got '{actual:?}'")]
    UnexpectedType {
        /// Name of the field that failed.
        name: &'static str,
        /// The expected datatype
        expected: DataType,
        /// The actual datatype.
        ///
        /// This is `None` if the actual datatype is unknown.
        actual: Option<DataType>,
    },

    /// Missing a required field
    #[error("missing required field for '{name}', expected '{expected}'")]
    MissingRequiredField {
        /// the name of the missing field
        name: &'static str,
        /// The expected datatype
        expected: DataType,
    },
}

/// A trait that allows converting from an application command interaction
pub trait FromOptions: std::fmt::Debug + Send
where
    Self: Sized,
{
    /// Make arguments from a [`CommandInteraction`]
    fn from_options(interaction: &CommandInteraction) -> Result<Self, ConvertError>;

    /// Get the argument paramss of this object
    fn get_argument_params() -> Result<Vec<ArgumentParam>, BuilderError> {
        Ok(Vec::new())
    }
}

// Allow the user to fill values while developing, or use a command with no arguments
impl FromOptions for () {
    fn from_options(_interaction: &CommandInteraction) -> Result<Self, ConvertError> {
        Ok(())
    }
}

/// A datatype
#[derive(Debug, Copy, Clone)]
pub enum DataType {
    /// A string
    String,

    /// Integer
    Integer,

    /// Bool
    Boolean,
}

impl DataType {
    /// Get this as a str
    pub fn as_str(self) -> &'static str {
        match self {
            Self::String => "String",
            Self::Integer => "i64",
            Self::Boolean => "bool",
        }
    }

    /// Get the type of a [`CommandDataOptionValue`].
    ///
    /// This returns an option as [`DataType`] does not encode the concept of an unknown data type.
    pub fn from_data_option_value(v: &CommandDataOptionValue) -> Option<Self> {
        match v {
            CommandDataOptionValue::String(_) => Some(DataType::String),
            CommandDataOptionValue::Integer(_) => Some(DataType::Integer),
            CommandDataOptionValue::Boolean(_) => Some(DataType::Boolean),
            _ => None,
        }
    }
}

impl std::fmt::Display for DataType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.as_str().fmt(f)
    }
}

/// Convert from an option value
pub trait FromOptionValue: Sized {
    /// Parse from an option value
    fn from_option_value(
        name: &'static str,
        option: &CommandDataOptionValue,
    ) -> Result<Self, ConvertError>;

    /// The expected data type
    fn get_expected_data_type() -> DataType;

    /// Kind of a hack to get the default "missing" value if the key was not present.
    ///
    /// # Returns
    /// Returns None if this type is not optional.
    fn get_missing_default() -> Option<Self> {
        None
    }
}

impl FromOptionValue for bool {
    fn from_option_value(
        name: &'static str,
        option: &CommandDataOptionValue,
    ) -> Result<Self, ConvertError> {
        let expected = Self::get_expected_data_type();

        match option {
            CommandDataOptionValue::Boolean(b) => Ok(*b),
            t => Err(ConvertError::UnexpectedType {
                name,
                expected,
                actual: DataType::from_data_option_value(t),
            }),
        }
    }

    fn get_expected_data_type() -> DataType {
        DataType::Boolean
    }
}

impl FromOptionValue for String {
    fn from_option_value(
        name: &'static str,
        option: &CommandDataOptionValue,
    ) -> Result<Self, ConvertError> {
        let expected = Self::get_expected_data_type();

        match option {
            CommandDataOptionValue::String(s) => Ok(s.clone()),
            t => Err(ConvertError::UnexpectedType {
                name,
                expected,
                actual: DataType::from_data_option_value(t),
            }),
        }
    }

    fn get_expected_data_type() -> DataType {
        DataType::String
    }
}

impl<T> FromOptionValue for Option<T>
where
    T: FromOptionValue,
{
    fn from_option_value(
        name: &'static str,
        option: &CommandDataOptionValue,
    ) -> Result<Self, ConvertError> {
        T::from_option_value(name, option).map(Some)
    }

    fn get_missing_default() -> Option<Self> {
        Some(None)
    }

    fn get_expected_data_type() -> DataType {
        T::get_expected_data_type()
    }
}