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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Create an [`Embed`] with a builder.

pub mod image_source;

mod author;
mod field;
mod footer;

pub use self::{
    author::EmbedAuthorBuilder, field::EmbedFieldBuilder, footer::EmbedFooterBuilder,
    image_source::ImageSource,
};

use twilight_model::{
    channel::message::embed::{
        Embed, EmbedAuthor, EmbedField, EmbedFooter, EmbedImage, EmbedThumbnail,
    },
    util::Timestamp,
};
use twilight_validate::embed::{embed as validate_embed, EmbedValidationError};

/// Create an [`Embed`] with a builder.
///
/// # Examples
///
/// Build a simple embed:
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_util::builder::embed::{EmbedBuilder, EmbedFieldBuilder};
///
/// let embed = EmbedBuilder::new()
///     .description("Here's a list of reasons why Twilight is the best pony:")
///     .field(EmbedFieldBuilder::new("Wings", "She has wings.").inline())
///     .field(
///         EmbedFieldBuilder::new("Horn", "She can do magic, and she's really good at it.")
///             .inline(),
///     )
///     .validate()?
///     .build();
/// # Ok(()) }
/// ```
///
/// Build an embed with an image:
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_util::builder::embed::{EmbedBuilder, ImageSource};
///
/// let embed = EmbedBuilder::new()
///     .description("Here's a cool image of Twilight Sparkle")
///     .image(ImageSource::attachment("bestpony.png")?)
///     .validate()?
///     .build();
/// # Ok(()) }
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
#[must_use = "must be built into an embed"]
pub struct EmbedBuilder(Embed);

impl EmbedBuilder {
    /// Create a new embed builder.
    pub fn new() -> Self {
        EmbedBuilder(Embed {
            author: None,
            color: None,
            description: None,
            fields: Vec::new(),
            footer: None,
            image: None,
            kind: "rich".to_owned(),
            provider: None,
            thumbnail: None,
            timestamp: None,
            title: None,
            url: None,
            video: None,
        })
    }

    /// Build this into an embed.
    #[allow(clippy::missing_const_for_fn)]
    #[must_use = "should be used as part of something like a message"]
    pub fn build(self) -> Embed {
        self.0
    }

    /// Ensure the embed is valid.
    ///
    /// # Errors
    ///
    /// Refer to the documentation of [`twilight_validate::embed::embed`] for
    /// possible errors.
    pub fn validate(self) -> Result<Self, EmbedValidationError> {
        #[allow(clippy::question_mark)]
        if let Err(source) = validate_embed(&self.0) {
            return Err(source);
        }

        Ok(self)
    }

    /// Set the author.
    ///
    /// # Examples
    ///
    /// Create an embed author:
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::{EmbedAuthorBuilder, EmbedBuilder};
    ///
    /// let author = EmbedAuthorBuilder::new("Twilight")
    ///     .url("https://github.com/twilight-rs/twilight")
    ///     .build();
    ///
    /// let embed = EmbedBuilder::new().author(author).validate()?.build();
    /// # Ok(()) }
    /// ```
    pub fn author(mut self, author: impl Into<EmbedAuthor>) -> Self {
        self.0.author = Some(author.into());

        self
    }

    /// Set the color.
    ///
    /// This must be a valid hexadecimal RGB value. Refer to
    /// [`COLOR_MAXIMUM`] for the maximum acceptable value.
    ///
    /// # Examples
    ///
    /// Set the color of an embed to `0xfd69b3`:
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::EmbedBuilder;
    ///
    /// let embed = EmbedBuilder::new()
    ///     .color(0xfd_69_b3)
    ///     .description("a description")
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    ///
    /// [`COLOR_MAXIMUM`]: twilight_validate::embed::COLOR_MAXIMUM
    pub const fn color(mut self, color: u32) -> Self {
        self.0.color = Some(color);

        self
    }

    /// Set the description.
    ///
    /// Refer to [`DESCRIPTION_LENGTH`] for the maximum number of UTF-16 code
    /// points that can be in a description.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::EmbedBuilder;
    ///
    /// let embed = EmbedBuilder::new()
    ///     .description("this is an embed")
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    ///
    /// [`DESCRIPTION_LENGTH`]: twilight_validate::embed::DESCRIPTION_LENGTH
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.0.description = Some(description.into());

        self
    }

    /// Add a field to the embed.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::{EmbedBuilder, EmbedFieldBuilder};
    ///
    /// let embed = EmbedBuilder::new()
    ///     .description("this is an embed")
    ///     .field(EmbedFieldBuilder::new("a field", "and its value"))
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    pub fn field(mut self, field: impl Into<EmbedField>) -> Self {
        self.0.fields.push(field.into());

        self
    }

    /// Set the footer of the embed.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::{EmbedBuilder, EmbedFooterBuilder};
    ///
    /// let embed = EmbedBuilder::new()
    ///     .description("this is an embed")
    ///     .footer(EmbedFooterBuilder::new("a footer"))
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    pub fn footer(mut self, footer: impl Into<EmbedFooter>) -> Self {
        self.0.footer = Some(footer.into());

        self
    }

    /// Set the image.
    ///
    /// # Examples
    ///
    /// Set the image source to a URL:
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::{EmbedBuilder, EmbedFooterBuilder, ImageSource};
    ///
    /// let source =
    ///     ImageSource::url("https://raw.githubusercontent.com/twilight-rs/twilight/main/logo.png")?;
    /// let embed = EmbedBuilder::new()
    ///     .footer(EmbedFooterBuilder::new("twilight"))
    ///     .image(source)
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    #[allow(clippy::missing_const_for_fn)]
    pub fn image(mut self, image_source: ImageSource) -> Self {
        self.0.image = Some(EmbedImage {
            height: None,
            proxy_url: None,
            url: image_source.0,
            width: None,
        });

        self
    }

    /// Add a thumbnail.
    ///
    /// # Examples
    ///
    /// Set the thumbnail to an image attachment with the filename
    /// `"twilight.png"`:
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::{EmbedBuilder, ImageSource};
    ///
    /// let embed = EmbedBuilder::new()
    ///     .description("a picture of twilight")
    ///     .thumbnail(ImageSource::attachment("twilight.png")?)
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    #[allow(clippy::missing_const_for_fn)]
    pub fn thumbnail(mut self, image_source: ImageSource) -> Self {
        self.0.thumbnail = Some(EmbedThumbnail {
            height: None,
            proxy_url: None,
            url: image_source.0,
            width: None,
        });

        self
    }

    /// Set the ISO 8601 timestamp.
    pub const fn timestamp(mut self, timestamp: Timestamp) -> Self {
        self.0.timestamp = Some(timestamp);

        self
    }

    /// Set the title.
    ///
    /// Refer to [`TITLE_LENGTH`] for the maximum number of UTF-16 code points
    /// that can be in a title.
    ///
    /// # Examples
    ///
    /// Set the title to "twilight":
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::EmbedBuilder;
    ///
    /// let embed = EmbedBuilder::new()
    ///     .title("twilight")
    ///     .url("https://github.com/twilight-rs/twilight")
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    ///
    /// [`TITLE_LENGTH`]: twilight_validate::embed::TITLE_LENGTH
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.0.title = Some(title.into());

        self
    }

    /// Set the URL.
    ///
    /// # Examples
    ///
    /// Set the URL to [twilight's repository]:
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use twilight_util::builder::embed::{EmbedBuilder, EmbedFooterBuilder};
    ///
    /// let embed = EmbedBuilder::new()
    ///     .description("twilight's repository")
    ///     .url("https://github.com/twilight-rs/twilight")
    ///     .validate()?
    ///     .build();
    /// # Ok(()) }
    /// ```
    ///
    /// [twilight's repository]: https://github.com/twilight-rs/twilight
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.0.url = Some(url.into());

        self
    }
}

impl Default for EmbedBuilder {
    /// Create an embed builder with a default embed.
    ///
    /// All embeds have a "rich" type.
    fn default() -> Self {
        Self::new()
    }
}

impl From<Embed> for EmbedBuilder {
    fn from(value: Embed) -> Self {
        Self(Embed {
            kind: "rich".to_owned(),
            ..value
        })
    }
}

impl TryFrom<EmbedBuilder> for Embed {
    type Error = EmbedValidationError;

    /// Convert an embed builder into an embed, validating its contents.
    ///
    /// This is equivalent to calling [`EmbedBuilder::validate`], then
    /// [`EmbedBuilder::build`].
    fn try_from(builder: EmbedBuilder) -> Result<Self, Self::Error> {
        Ok(builder.validate()?.build())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use static_assertions::assert_impl_all;
    use std::fmt::Debug;

    assert_impl_all!(EmbedBuilder: Clone, Debug, Eq, PartialEq, Send, Sync);
    assert_impl_all!(Embed: TryFrom<EmbedBuilder>);

    #[test]
    fn builder() {
        let footer_image = ImageSource::url(
            "https://raw.githubusercontent.com/twilight-rs/twilight/main/logo.png",
        )
        .unwrap();
        let timestamp = Timestamp::from_secs(1_580_608_922).expect("non zero");

        let embed = EmbedBuilder::new()
            .color(0x00_43_ff)
            .description("Description")
            .timestamp(timestamp)
            .footer(EmbedFooterBuilder::new("Warn").icon_url(footer_image))
            .field(EmbedFieldBuilder::new("name", "title").inline())
            .build();

        let expected = Embed {
            author: None,
            color: Some(0x00_43_ff),
            description: Some("Description".to_string()),
            fields: [EmbedField {
                inline: true,
                name: "name".to_string(),
                value: "title".to_string(),
            }]
            .to_vec(),
            footer: Some(EmbedFooter {
                icon_url: Some(
                    "https://raw.githubusercontent.com/twilight-rs/twilight/main/logo.png"
                        .to_string(),
                ),
                proxy_icon_url: None,
                text: "Warn".to_string(),
            }),
            image: None,
            kind: "rich".to_string(),
            provider: None,
            thumbnail: None,
            timestamp: Some(timestamp),
            title: None,
            url: None,
            video: None,
        };

        assert_eq!(embed, expected);
    }
}