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
429
430
//! Formatters for creating mentions.

use super::timestamp::Timestamp;
use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use twilight_model::{
    channel::Channel,
    guild::{Emoji, Member, Role},
    id::{
        marker::{ChannelMarker, CommandMarker, EmojiMarker, RoleMarker, UserMarker},
        Id,
    },
    user::{CurrentUser, User},
};

/// Formatter to mention a resource that implements `std::fmt::Display`.
///
/// # Examples
///
/// Mention a `Id<UserMarker>`:
///
/// ```
/// use twilight_mention::Mention;
/// use twilight_model::id::{marker::UserMarker, Id};
///
/// assert_eq!("<@123>", Id::<UserMarker>::new(123).mention().to_string());
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MentionFormat<T>(T);

/// Mention a channel. This will format as `<#ID>`.
impl Display for MentionFormat<Id<ChannelMarker>> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("<#")?;
        Display::fmt(&self.0, f)?;

        f.write_str(">")
    }
}

/// Mention a command. This will format as:
/// - `</NAME:COMMAND_ID>` for commands
/// - `</NAME SUBCOMMAND:ID>` for subcommands
/// - `</NAME SUBCOMMAND_GROUP SUBCOMMAND:ID>` for subcommand groups
impl Display for MentionFormat<CommandMention> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("</")?;

        match &self.0 {
            CommandMention::Command { name, id } => {
                // </NAME:COMMAND_ID>
                f.write_str(name)?;
                f.write_char(':')?;
                Display::fmt(id, f)?;
            }
            CommandMention::SubCommand {
                name,
                sub_command,
                id,
            } => {
                // </NAME SUBCOMMAND:ID>
                f.write_str(name)?;
                f.write_char(' ')?;
                f.write_str(sub_command)?;
                f.write_char(':')?;
                Display::fmt(id, f)?;
            }
            CommandMention::SubCommandGroup {
                name,
                sub_command_group,
                sub_command,
                id,
            } => {
                // </NAME SUBCOMMAND_GROUP SUBCOMMAND:ID>
                f.write_str(name)?;
                f.write_char(' ')?;
                f.write_str(sub_command_group)?;
                f.write_char(' ')?;
                f.write_str(sub_command)?;
                f.write_char(':')?;
                Display::fmt(id, f)?;
            }
        }

        f.write_char('>')
    }
}

/// Mention an emoji. This will format as `<:emoji:ID>`.
impl Display for MentionFormat<Id<EmojiMarker>> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("<:emoji:")?;
        Display::fmt(&self.0, f)?;

        f.write_str(">")
    }
}

/// Mention a role. This will format as `<@&ID>`.
impl Display for MentionFormat<Id<RoleMarker>> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("<@&")?;
        Display::fmt(&self.0, f)?;

        f.write_str(">")
    }
}

/// Mention a user. This will format as `<t:UNIX>` if a style is not specified or
/// `<t:UNIX:STYLE>` if a style is specified.
impl Display for MentionFormat<Timestamp> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("<t:")?;
        Display::fmt(&self.0.unix(), f)?;

        if let Some(style) = self.0.style() {
            f.write_str(":")?;
            Display::fmt(&style, f)?;
        }

        f.write_str(">")
    }
}

/// Mention a user. This will format as `<@ID>`.
impl Display for MentionFormat<Id<UserMarker>> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("<@")?;
        Display::fmt(&self.0, f)?;

        f.write_str(">")
    }
}

/// Mention a resource, such as an emoji or user.
///
/// This will create a mention that will link to a user if it exists.
///
/// Look at the implementations list to see what you can mention.
///
/// # Examples
///
/// Mention a channel ID:
///
/// ```
/// use twilight_mention::Mention;
/// use twilight_model::id::{marker::ChannelMarker, Id};
///
/// let id = Id::<ChannelMarker>::new(123);
/// assert_eq!("<#123>", id.mention().to_string());
/// ```
pub trait Mention<T> {
    /// Mention a resource by using its ID.
    fn mention(&self) -> MentionFormat<T>;
}

impl<T, M: Mention<T>> Mention<T> for &'_ M {
    fn mention(&self) -> MentionFormat<T> {
        (*self).mention()
    }
}

/// Mention a channel ID. This will format as `<#ID>`.
impl Mention<Id<ChannelMarker>> for Id<ChannelMarker> {
    fn mention(&self) -> MentionFormat<Id<ChannelMarker>> {
        MentionFormat(*self)
    }
}

/// Mention a channel. This will format as `<#ID>`.
impl Mention<Id<ChannelMarker>> for Channel {
    fn mention(&self) -> MentionFormat<Id<ChannelMarker>> {
        MentionFormat(self.id)
    }
}

/// Mention a command.
///
/// This will format as:
/// - `</NAME:COMMAND_ID>` for commands
/// - `</NAME SUBCOMMAND:ID>` for subcommands
/// - `</NAME SUBCOMMAND_GROUP SUBCOMMAND:ID>` for subcommand groups
///
/// # Cloning
///
/// This implementation uses [`clone`](Clone::clone) to construct a [`MentionFormat`] that owns the
/// inner `CommandMention` as [`mention`](Mention::mention) takes a `&self`.
/// The other implementations do this for types that are [`Copy`] and therefore do not need to use
/// [`clone`](Clone::clone).
///
/// To avoid cloning use [`CommandMention::into_mention`].
impl Mention<CommandMention> for CommandMention {
    fn mention(&self) -> MentionFormat<CommandMention> {
        MentionFormat(self.clone())
    }
}

impl CommandMention {
    /// Mention a command.
    ///
    /// This will format as:
    /// - `</NAME:COMMAND_ID>` for commands
    /// - `</NAME SUBCOMMAND:ID>` for subcommands
    /// - `</NAME SUBCOMMAND_GROUP SUBCOMMAND:ID>` for subcommand groups
    ///
    /// This is a self-consuming alternative to [`CommandMention::mention`] and avoids cloning.
    pub const fn into_mention(self) -> MentionFormat<CommandMention> {
        MentionFormat(self)
    }
}

/// Mention the current user. This will format as `<@ID>`.
impl Mention<Id<UserMarker>> for CurrentUser {
    fn mention(&self) -> MentionFormat<Id<UserMarker>> {
        MentionFormat(self.id)
    }
}

/// Mention an emoji. This will format as `<:emoji:ID>`.
impl Mention<Id<EmojiMarker>> for Id<EmojiMarker> {
    fn mention(&self) -> MentionFormat<Id<EmojiMarker>> {
        MentionFormat(*self)
    }
}

/// Mention an emoji. This will format as `<:emoji:ID>`.
impl Mention<Id<EmojiMarker>> for Emoji {
    fn mention(&self) -> MentionFormat<Id<EmojiMarker>> {
        MentionFormat(self.id)
    }
}

/// Mention a member's user. This will format as `<@ID>`.
impl Mention<Id<UserMarker>> for Member {
    fn mention(&self) -> MentionFormat<Id<UserMarker>> {
        MentionFormat(self.user.id)
    }
}

/// Mention a role ID. This will format as `<@&ID>`.
impl Mention<Id<RoleMarker>> for Id<RoleMarker> {
    fn mention(&self) -> MentionFormat<Id<RoleMarker>> {
        MentionFormat(*self)
    }
}

/// Mention a role ID. This will format as `<@&ID>`.
impl Mention<Id<RoleMarker>> for Role {
    fn mention(&self) -> MentionFormat<Id<RoleMarker>> {
        MentionFormat(self.id)
    }
}

/// Mention a timestamp. This will format as `<t:UNIX>` if a style is not
/// specified or `<t:UNIX:STYLE>` if a style is specified.
impl Mention<Self> for Timestamp {
    fn mention(&self) -> MentionFormat<Self> {
        MentionFormat(*self)
    }
}

/// Mention a user ID. This will format as `<&ID>`.
impl Mention<Id<UserMarker>> for Id<UserMarker> {
    fn mention(&self) -> MentionFormat<Id<UserMarker>> {
        MentionFormat(*self)
    }
}

/// Mention a user. This will format as `<&ID>`.
impl Mention<Id<UserMarker>> for User {
    fn mention(&self) -> MentionFormat<Id<UserMarker>> {
        MentionFormat(self.id)
    }
}

/// Components to construct a slash command mention.
///
/// Format slash commands, subcommands and subcommand groups.
/// See [Discord Docs/Message Formatting].
/// See [Discord Docs Changelog/Slash Command Mentions].
///
/// [Discord Docs/Message Formatting]: https://discord.com/developers/docs/reference#message-formatting
/// [Discord Docs Changelog/Slash Command Mentions]: https://discord.com/developers/docs/change-log#slash-command-mentions
#[allow(missing_docs)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CommandMention {
    Command {
        id: Id<CommandMarker>,
        name: String,
    },

    SubCommand {
        id: Id<CommandMarker>,
        name: String,
        sub_command: String,
    },

    SubCommandGroup {
        id: Id<CommandMarker>,
        name: String,
        sub_command: String,
        sub_command_group: String,
    },
}

#[cfg(test)]
mod tests {
    use crate::timestamp::{Timestamp, TimestampStyle};

    use super::{CommandMention, Mention, MentionFormat};
    use static_assertions::assert_impl_all;
    use std::fmt::{Debug, Display};
    use twilight_model::id::marker::CommandMarker;
    use twilight_model::{
        channel::Channel,
        guild::{Emoji, Member, Role},
        id::{
            marker::{ChannelMarker, EmojiMarker, RoleMarker, UserMarker},
            Id,
        },
        user::{CurrentUser, User},
    };

    assert_impl_all!(MentionFormat<()>: Clone, Copy, Debug, Eq, PartialEq, Send, Sync);
    assert_impl_all!(MentionFormat<Id<ChannelMarker>>: Clone, Copy, Debug, Display, Eq, PartialEq, Send, Sync);
    assert_impl_all!(MentionFormat<CommandMention>: Clone, Debug, Display, Eq, PartialEq, Send, Sync);
    assert_impl_all!(MentionFormat<Id<EmojiMarker>>: Clone, Copy, Debug, Display, Eq, PartialEq, Send, Sync);
    assert_impl_all!(MentionFormat<Id<RoleMarker>>: Clone, Copy, Debug, Display, Eq, PartialEq, Send, Sync);
    assert_impl_all!(MentionFormat<Id<UserMarker>>: Clone, Copy, Debug, Display, Eq, PartialEq, Send, Sync);
    assert_impl_all!(Id<ChannelMarker>: Mention<Id<ChannelMarker>>);
    assert_impl_all!(&'static Id<ChannelMarker>: Mention<Id<ChannelMarker>>);
    assert_impl_all!(Channel: Mention<Id<ChannelMarker>>);
    assert_impl_all!(&'static Channel: Mention<Id<ChannelMarker>>);
    assert_impl_all!(CurrentUser: Mention<Id<UserMarker>>);
    assert_impl_all!(&'static CurrentUser: Mention<Id<UserMarker>>);
    assert_impl_all!(Id<EmojiMarker>: Mention<Id<EmojiMarker>>);
    assert_impl_all!(&'static Id<EmojiMarker>: Mention<Id<EmojiMarker>>);
    assert_impl_all!(Emoji: Mention<Id<EmojiMarker>>);
    assert_impl_all!(&'static Emoji: Mention<Id<EmojiMarker>>);
    assert_impl_all!(Member: Mention<Id<UserMarker>>);
    assert_impl_all!(&'static Member: Mention<Id<UserMarker>>);
    assert_impl_all!(Id<RoleMarker>: Mention<Id<RoleMarker>>);
    assert_impl_all!(&'static Id<RoleMarker>: Mention<Id<RoleMarker>>);
    assert_impl_all!(Role: Mention<Id<RoleMarker>>);
    assert_impl_all!(&'static Role: Mention<Id<RoleMarker>>);
    assert_impl_all!(Id<UserMarker>: Mention<Id<UserMarker>>);
    assert_impl_all!(&'static Id<UserMarker>: Mention<Id<UserMarker>>);
    assert_impl_all!(User: Mention<Id<UserMarker>>);
    assert_impl_all!(&'static User: Mention<Id<UserMarker>>);

    #[test]
    fn mention_format_channel_id() {
        assert_eq!(
            "<#123>",
            Id::<ChannelMarker>::new(123).mention().to_string()
        );
    }

    #[test]
    fn mention_format_command() {
        assert_eq!(
            "</name:123>",
            MentionFormat(CommandMention::Command {
                id: Id::<CommandMarker>::new(123),
                name: "name".to_string()
            })
            .to_string()
        );
    }

    #[test]
    fn mention_format_sub_command() {
        assert_eq!(
            "</name subcommand:123>",
            MentionFormat(CommandMention::SubCommand {
                id: Id::<CommandMarker>::new(123),
                name: "name".to_string(),
                sub_command: "subcommand".to_string()
            })
            .to_string()
        );
    }

    #[test]
    fn mention_format_sub_command_group() {
        assert_eq!(
            "</name subcommand_group subcommand:123>",
            MentionFormat(CommandMention::SubCommandGroup {
                id: Id::<CommandMarker>::new(123),
                name: "name".to_string(),
                sub_command: "subcommand".to_string(),
                sub_command_group: "subcommand_group".to_string()
            })
            .to_string()
        );
    }

    #[test]
    fn mention_format_emoji_id() {
        assert_eq!(
            "<:emoji:123>",
            Id::<EmojiMarker>::new(123).mention().to_string()
        );
    }

    #[test]
    fn mention_format_role_id() {
        assert_eq!("<@&123>", Id::<RoleMarker>::new(123).mention().to_string());
    }

    /// Test that a timestamp with a style displays correctly.
    #[test]
    fn mention_format_timestamp_styled() {
        let timestamp = Timestamp::new(1_624_047_064, Some(TimestampStyle::RelativeTime));

        assert_eq!("<t:1624047064:R>", timestamp.mention().to_string());
    }

    /// Test that a timestamp without a style displays correctly.
    #[test]
    fn mention_format_timestamp_unstyled() {
        let timestamp = Timestamp::new(1_624_047_064, None);

        assert_eq!("<t:1624047064>", timestamp.mention().to_string());
    }

    #[test]
    fn mention_format_user_id() {
        assert_eq!("<@123>", Id::<UserMarker>::new(123).mention().to_string());
    }
}