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
use crate::{
    client::Client,
    error::Error,
    request::{self, AuditLogReason, Nullable, Request, TryIntoRequest},
    response::{Response, ResponseFuture},
    routing::Route,
};
use serde::Serialize;
use std::future::IntoFuture;
use twilight_model::{
    guild::{
        DefaultMessageNotificationLevel, ExplicitContentFilter, PartialGuild, SystemChannelFlags,
        VerificationLevel,
    },
    id::{
        marker::{ChannelMarker, GuildMarker, UserMarker},
        Id,
    },
};
use twilight_validate::request::{
    audit_reason as validate_audit_reason, guild_name as validate_guild_name, ValidationError,
};

#[derive(Serialize)]
struct UpdateGuildFields<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    afk_channel_id: Option<Nullable<Id<ChannelMarker>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    afk_timeout: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    banner: Option<Nullable<&'a str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    default_message_notifications: Option<Nullable<DefaultMessageNotificationLevel>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    discovery_splash: Option<Nullable<&'a str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    explicit_content_filter: Option<Nullable<ExplicitContentFilter>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    features: Option<&'a [&'a str]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<Nullable<&'a str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    owner_id: Option<Id<UserMarker>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    splash: Option<Nullable<&'a str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    system_channel_id: Option<Nullable<Id<ChannelMarker>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    system_channel_flags: Option<Nullable<SystemChannelFlags>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    verification_level: Option<Nullable<VerificationLevel>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    rules_channel_id: Option<Nullable<Id<ChannelMarker>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    public_updates_channel_id: Option<Nullable<Id<ChannelMarker>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    preferred_locale: Option<Nullable<&'a str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    premium_progress_bar_enabled: Option<bool>,
}

/// Update a guild.
///
/// All endpoints are optional. See [Discord Docs/Modify Guild].
///
/// [Discord Docs/Modify Guild]: https://discord.com/developers/docs/resources/guild#modify-guild
#[must_use = "requests must be configured and executed"]
pub struct UpdateGuild<'a> {
    fields: UpdateGuildFields<'a>,
    guild_id: Id<GuildMarker>,
    http: &'a Client,
    reason: Option<&'a str>,
}

impl<'a> UpdateGuild<'a> {
    pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {
        Self {
            fields: UpdateGuildFields {
                afk_channel_id: None,
                afk_timeout: None,
                banner: None,
                default_message_notifications: None,
                discovery_splash: None,
                explicit_content_filter: None,
                features: None,
                icon: None,
                name: None,
                owner_id: None,
                splash: None,
                system_channel_id: None,
                system_channel_flags: None,
                verification_level: None,
                rules_channel_id: None,
                public_updates_channel_id: None,
                preferred_locale: None,
                premium_progress_bar_enabled: None,
            },
            guild_id,
            http,
            reason: None,
        }
    }

    /// Set the voice channel where AFK voice users are sent.
    pub const fn afk_channel_id(mut self, afk_channel_id: Option<Id<ChannelMarker>>) -> Self {
        self.fields.afk_channel_id = Some(Nullable(afk_channel_id));

        self
    }

    /// Set how much time it takes for a voice user to be considered AFK.
    pub const fn afk_timeout(mut self, afk_timeout: u64) -> Self {
        self.fields.afk_timeout = Some(afk_timeout);

        self
    }

    /// Set the banner.
    ///
    /// This is a base64 encoded 16:9 PNG or JPEG image. Pass `None` to remove
    /// the banner.
    ///
    /// The server must have the `BANNER` feature.
    pub const fn banner(mut self, banner: Option<&'a str>) -> Self {
        self.fields.banner = Some(Nullable(banner));

        self
    }

    /// Set the default message notification level. See
    /// [Discord Docs/Create Guild] for more information.
    ///
    /// [Discord Docs/Create Guild]: https://discord.com/developers/docs/resources/guild#create-guild
    pub const fn default_message_notifications(
        mut self,
        default_message_notifications: Option<DefaultMessageNotificationLevel>,
    ) -> Self {
        self.fields.default_message_notifications = Some(Nullable(default_message_notifications));

        self
    }

    /// Set the guild's discovery splash image.
    ///
    /// Requires the guild to have the `DISCOVERABLE` feature enabled.
    pub const fn discovery_splash(mut self, discovery_splash: Option<&'a str>) -> Self {
        self.fields.discovery_splash = Some(Nullable(discovery_splash));

        self
    }

    /// Set the explicit content filter level.
    pub const fn explicit_content_filter(
        mut self,
        explicit_content_filter: Option<ExplicitContentFilter>,
    ) -> Self {
        self.fields.explicit_content_filter = Some(Nullable(explicit_content_filter));

        self
    }

    /// Set the enabled features of the guild.
    ///
    /// Attempting to add or remove the [`GuildFeature::Community`] feature requires the
    /// [`Permissions::ADMINISTRATOR`] permission.
    ///
    /// Attempting to add or remove the [`GuildFeature::Discoverable`] feature requires
    /// the [`Permissions::ADMINISTRATOR`] permission. Additionally the guild
    /// must pass all the discovery requirements.
    ///
    /// Attempting to add or remove the [`GuildFeature::InvitesDisabled`] feature requires
    /// the [`Permissions::MANAGE_GUILD`] permission.
    ///
    /// [`GuildFeature::Community`]: twilight_model::guild::GuildFeature::Community
    /// [`GuildFeature::Discoverable`]: twilight_model::guild::GuildFeature::Discoverable
    /// [`GuildFeature::InvitesDisabled`]: twilight_model::guild::GuildFeature::InvitesDisabled
    /// [`Permissions::ADMINISTRATOR`]: twilight_model::guild::Permissions::ADMINISTRATOR
    /// [`Permissions::MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
    pub const fn features(mut self, features: &'a [&'a str]) -> Self {
        self.fields.features = Some(features);

        self
    }

    /// Set the icon.
    ///
    /// This must be a Data URI, in the form of
    /// `data:image/{type};base64,{data}` where `{type}` is the image MIME type
    /// and `{data}` is the base64-encoded image. See [Discord Docs/Image Data].
    ///
    /// [Discord Docs/Image Data]: https://discord.com/developers/docs/reference#image-data
    pub const fn icon(mut self, icon: Option<&'a str>) -> Self {
        self.fields.icon = Some(Nullable(icon));

        self
    }

    /// Set the name of the guild.
    ///
    /// The minimum length is 1 UTF-16 character and the maximum is 100 UTF-16
    /// characters.
    ///
    /// # Errors
    ///
    /// Returns an error of type [`GuildName`] if the name length is too short
    /// or too long.
    ///
    /// [`GuildName`]: twilight_validate::request::ValidationErrorType::GuildName
    pub fn name(mut self, name: &'a str) -> Result<Self, ValidationError> {
        validate_guild_name(name)?;

        self.fields.name.replace(name);

        Ok(self)
    }

    /// Transfer ownership to another user.
    ///
    /// Only works if the current user is the owner.
    pub const fn owner_id(mut self, owner_id: Id<UserMarker>) -> Self {
        self.fields.owner_id = Some(owner_id);

        self
    }

    /// Set the guild's splash image.
    ///
    /// Requires the guild to have the `INVITE_SPLASH` feature enabled.
    pub const fn splash(mut self, splash: Option<&'a str>) -> Self {
        self.fields.splash = Some(Nullable(splash));

        self
    }

    /// Set the channel where events such as welcome messages are posted.
    pub const fn system_channel(mut self, system_channel_id: Option<Id<ChannelMarker>>) -> Self {
        self.fields.system_channel_id = Some(Nullable(system_channel_id));

        self
    }

    /// Set the guild's [`SystemChannelFlags`].
    pub const fn system_channel_flags(
        mut self,
        system_channel_flags: Option<SystemChannelFlags>,
    ) -> Self {
        self.fields.system_channel_flags = Some(Nullable(system_channel_flags));

        self
    }

    /// Set the rules channel.
    ///
    /// Requires the guild to be `PUBLIC`. See [Discord Docs/Modify Guild].
    ///
    /// [Discord Docs/Modify Guild]: https://discord.com/developers/docs/resources/guild#modify-guild
    pub const fn rules_channel(mut self, rules_channel_id: Option<Id<ChannelMarker>>) -> Self {
        self.fields.rules_channel_id = Some(Nullable(rules_channel_id));

        self
    }

    /// Set the public updates channel.
    ///
    /// Requires the guild to be `PUBLIC`.
    pub const fn public_updates_channel(
        mut self,
        public_updates_channel_id: Option<Id<ChannelMarker>>,
    ) -> Self {
        self.fields.public_updates_channel_id = Some(Nullable(public_updates_channel_id));

        self
    }

    /// Set the preferred locale for the guild.
    ///
    /// Defaults to `en-US`. Requires the guild to be `PUBLIC`.
    pub const fn preferred_locale(mut self, preferred_locale: Option<&'a str>) -> Self {
        self.fields.preferred_locale = Some(Nullable(preferred_locale));

        self
    }

    /// Set the verification level.
    ///
    /// See [Discord Docs/Guild Object].
    ///
    /// [Discord Docs/Guild Object]: https://discord.com/developers/docs/resources/guild#guild-object-verification-level
    pub const fn verification_level(
        mut self,
        verification_level: Option<VerificationLevel>,
    ) -> Self {
        self.fields.verification_level = Some(Nullable(verification_level));

        self
    }

    /// Set whether the premium progress bar is enabled.
    pub const fn premium_progress_bar_enabled(
        mut self,
        premium_progress_bar_enabled: bool,
    ) -> Self {
        self.fields.premium_progress_bar_enabled = Some(premium_progress_bar_enabled);

        self
    }

    /// Execute the request, returning a future resolving to a [`Response`].
    #[deprecated(since = "0.14.0", note = "use `.await` or `into_future` instead")]
    pub fn exec(self) -> ResponseFuture<PartialGuild> {
        self.into_future()
    }
}

impl<'a> AuditLogReason<'a> for UpdateGuild<'a> {
    fn reason(mut self, reason: &'a str) -> Result<Self, ValidationError> {
        validate_audit_reason(reason)?;

        self.reason.replace(reason);

        Ok(self)
    }
}

impl IntoFuture for UpdateGuild<'_> {
    type Output = Result<Response<PartialGuild>, Error>;

    type IntoFuture = ResponseFuture<PartialGuild>;

    fn into_future(self) -> Self::IntoFuture {
        let http = self.http;

        match self.try_into_request() {
            Ok(request) => http.request(request),
            Err(source) => ResponseFuture::error(source),
        }
    }
}

impl TryIntoRequest for UpdateGuild<'_> {
    fn try_into_request(self) -> Result<Request, Error> {
        let mut request = Request::builder(&Route::UpdateGuild {
            guild_id: self.guild_id.get(),
        });

        request = request.json(&self.fields)?;

        if let Some(reason) = &self.reason {
            let header = request::audit_header(reason)?;

            request = request.headers(header);
        }

        Ok(request.build())
    }
}