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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use chrono::{DateTime, Utc};
use serde::Serialize;
use serde_json::Value;

use crate::{
    auth::{AuthFlow, Verifier},
    error::Result,
    model::{
        playlist::{
            FeaturedPlaylists, Playlist, PlaylistTrack, Playlists, SimplifiedPlaylist, SnapshotId,
        },
        Page,
    },
    Nil,
};

use super::{Builder, Endpoint, Limit, PrivateEndpoint};

impl Endpoint for PlaylistEndpoint {}
impl Endpoint for ChangePlaylistDetailsEndpoint {}
impl Endpoint for PlaylistItemsEndpoint {}
impl Endpoint for UpdatePlaylistItemsEndpoint {}
impl Endpoint for AddPlaylistItemsEndpoint {}
impl Endpoint for RemovePlaylistItemsEndpoint {}
impl Endpoint for CurrentUserPlaylistsEndpoint {}
impl Endpoint for UserPlaylistsEndpoint {}
impl Endpoint for CreatePlaylistEndpoint<'_> {}
impl Endpoint for FeaturedPlaylistsEndpoint {}
impl Endpoint for CategoryPlaylistsEndpoint {}

#[derive(Clone, Debug, Default, Serialize)]
pub struct PlaylistEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    pub(crate) market: Option<String>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, PlaylistEndpoint> {
    #[doc = include_str!("../docs/market.md")]
    pub fn market(mut self, market: impl Into<String>) -> Self {
        self.endpoint.market = Some(market.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn get(self) -> Result<Playlist> {
        self.spotify
            .get(format!("/playlists/{}", self.endpoint.id), self.endpoint)
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct ChangePlaylistDetailsEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) public: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) collaborative: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) description: Option<String>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, ChangePlaylistDetailsEndpoint> {
    /// The new name for the playlist.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.endpoint.name = Some(name.into());
        self
    }

    /// Whether or not to make the playlist public.
    pub fn public(mut self, public: bool) -> Self {
        self.endpoint.public = Some(public);
        self
    }

    /// If true, other users will be able to modify the playlist.
    ///
    /// You can only set `collaborative` to `true` on private playlists.
    pub fn collaborative(mut self, collaborative: bool) -> Self {
        self.endpoint.collaborative = Some(collaborative);
        self
    }

    /// The new description for the playlist.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.endpoint.description = Some(description.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self) -> Result<Nil> {
        self.spotify
            .put(
                format!("/playlists/{}", self.endpoint.id),
                self.endpoint.json(),
            )
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct PlaylistItemsEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    pub(crate) market: Option<String>,
    pub(crate) limit: Option<Limit>,
    pub(crate) offset: Option<u32>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, PlaylistItemsEndpoint> {
    #[doc = include_str!("../docs/market.md")]
    pub fn market(mut self, market: impl Into<String>) -> Self {
        self.endpoint.market = Some(market.into());
        self
    }

    #[doc = include_str!("../docs/limit.md")]
    pub fn limit(mut self, limit: u32) -> Self {
        self.endpoint.limit = Some(Limit::new(limit));
        self
    }

    #[doc = include_str!("../docs/offset.md")]
    pub fn offset(mut self, offset: u32) -> Self {
        self.endpoint.offset = Some(offset);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn get(self) -> Result<Page<PlaylistTrack>> {
        self.spotify
            .get(
                format!("/playlists/{}/tracks", self.endpoint.id),
                self.endpoint,
            )
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct UpdatePlaylistItemsEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    pub(crate) range_start: u32,
    pub(crate) insert_before: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) uris: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) range_length: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) snapshot_id: Option<String>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, UpdatePlaylistItemsEndpoint> {
    /// The Spotify *URIs* of the items to add (an item can be a track or episode).
    pub fn uris<T: ToString>(mut self, uris: &[T]) -> Self {
        self.endpoint.uris = Some(uris.iter().map(ToString::to_string).collect());
        self
    }

    /// The amount of items to be reordered. Defaults to `1`.
    ///
    /// The range of items to be reordered begins from the range_start position,
    /// and includes the range_length subsequent items.
    ///
    /// For example, to move the items at index 9-10 to the start of the playlist,
    /// `range_start` should be 9 and `range_length` 2.
    pub fn range_length(mut self, range_length: u32) -> Self {
        self.endpoint.range_length = Some(range_length);
        self
    }

    /// The playlist's snapshot ID against which to make changes.
    pub fn snapshot_id(mut self, snapshot_id: impl Into<String>) -> Self {
        self.endpoint.snapshot_id = Some(snapshot_id.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self) -> Result<String> {
        self.spotify
            .put(
                format!("/playlists/{}/tracks", self.endpoint.id),
                self.endpoint.json(),
            )
            .await
            .map(|i: SnapshotId| i.snapshot_id)
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct AddPlaylistItemsEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    pub(crate) uris: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) position: Option<u32>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, AddPlaylistItemsEndpoint> {
    /// The position to insert the items at, zero-based. If omitted, items will be appended to the playlist.
    pub fn position(mut self, position: u32) -> Self {
        self.endpoint.position = Some(position);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self) -> Result<String> {
        self.spotify
            .post(
                format!("/playlists/{}/tracks", self.endpoint.id),
                self.endpoint.json(),
            )
            .await
            .map(|i: SnapshotId| i.snapshot_id)
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct RemovePlaylistItemsEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    pub(crate) tracks: Vec<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) snapshot_id: Option<String>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, RemovePlaylistItemsEndpoint> {
    /// The playlist's snapshot ID against which to make changes.
    pub fn snapshot_id(mut self, snapshot_id: impl Into<String>) -> Self {
        self.endpoint.snapshot_id = Some(snapshot_id.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]

    pub async fn send(self) -> Result<String> {
        self.spotify
            .delete(
                format!("/playlists/{}/tracks", self.endpoint.id),
                self.endpoint.json(),
            )
            .await
            .map(|i: SnapshotId| i.snapshot_id)
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct CurrentUserPlaylistsEndpoint {
    pub(crate) limit: Option<Limit>,
    pub(crate) offset: Option<u32>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, CurrentUserPlaylistsEndpoint> {
    #[doc = include_str!("../docs/limit.md")]
    pub fn limit(mut self, limit: u32) -> Self {
        self.endpoint.limit = Some(Limit::new(limit));
        self
    }

    #[doc = include_str!("../docs/offset.md")]
    pub fn offset(mut self, offset: u32) -> Self {
        self.endpoint.offset = Some(offset);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn get(self) -> Result<Page<SimplifiedPlaylist>> {
        self.spotify
            .get("/me/playlists".to_owned(), self.endpoint)
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct UserPlaylistsEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    pub(crate) limit: Option<Limit>,
    pub(crate) offset: Option<u32>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, UserPlaylistsEndpoint> {
    #[doc = include_str!("../docs/limit.md")]
    pub fn limit(mut self, limit: u32) -> Self {
        self.endpoint.limit = Some(Limit::new(limit));
        self
    }

    #[doc = include_str!("../docs/offset.md")]
    pub fn offset(mut self, offset: u32) -> Self {
        self.endpoint.offset = Some(offset);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn get(self) -> Result<Page<SimplifiedPlaylist>> {
        self.spotify
            .get(
                format!("/users/{}/playlists", self.endpoint.id),
                self.endpoint,
            )
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct CreatePlaylistEndpoint<'a> {
    #[serde(skip)]
    pub(crate) user_id: String,
    #[serde(skip)]
    pub(crate) tracks: Option<&'a [&'a str]>,
    pub(crate) name: String,
    pub(crate) public: Option<bool>,
    pub(crate) collaborative: Option<bool>,
    pub(crate) description: Option<String>,
}

impl<'a, F: AuthFlow, V: Verifier> Builder<'_, F, V, CreatePlaylistEndpoint<'a>> {
    /// Whether or not to make the playlist public. Defaults to `true`.
    pub fn public(mut self, public: bool) -> Self {
        self.endpoint.public = Some(public);
        self
    }

    /// If true, other users will be able to modify the playlist.
    ///
    /// You can only set `collaborative` to `true` on private playlists.
    /// Defaults to `false`.
    pub fn collaborative(mut self, collaborative: bool) -> Self {
        self.endpoint.collaborative = Some(collaborative);
        self
    }

    /// The description for the new playlist.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.endpoint.description = Some(description.into());
        self
    }

    pub fn tracks(mut self, track_uris: &'a [&str]) -> Self {
        self.endpoint.tracks = Some(track_uris);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self) -> Result<Playlist> {
        let tracks = self.endpoint.tracks;

        let mut playlist: Playlist = self
            .spotify
            .post(
                format!("/users/{}/playlists", self.endpoint.user_id),
                self.endpoint.json(),
            )
            .await?;

        if let Some(tracks) = tracks {
            self.spotify
                .add_items_to_playlist(&playlist.id, tracks)
                .send()
                .await?;

            let tracks = self.spotify.playlist_items(&playlist.id).get().await?;
            playlist.tracks = tracks;
        }

        Ok(playlist)
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct FeaturedPlaylistsEndpoint {
    pub(crate) country: Option<String>,
    pub(crate) locale: Option<String>,
    pub(crate) timestamp: Option<String>,
    pub(crate) limit: Option<Limit>,
    pub(crate) offset: Option<u32>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, FeaturedPlaylistsEndpoint> {
    #[doc = include_str!("../docs/country.md")]
    pub fn country(mut self, country: impl Into<String>) -> Self {
        self.endpoint.country = Some(country.into());
        self
    }

    #[doc = include_str!("../docs/locale.md")]
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.endpoint.locale = Some(locale.into());
        self
    }

    /// An [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp (`yyyy-MM-ddTHH:mm:ss`)
    pub fn timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
        self.endpoint.timestamp = Some(timestamp.to_rfc3339());
        self
    }

    #[doc = include_str!("../docs/limit.md")]
    pub fn limit(mut self, limit: u32) -> Self {
        self.endpoint.limit = Some(Limit::new(limit));
        self
    }

    #[doc = include_str!("../docs/offset.md")]
    pub fn offset(mut self, offset: u32) -> Self {
        self.endpoint.offset = Some(offset);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn get(self) -> Result<FeaturedPlaylists> {
        self.spotify
            .get("/browse/featured-playlists".to_owned(), self.endpoint)
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct CategoryPlaylistsEndpoint {
    #[serde(skip)]
    pub(crate) id: String,
    pub(crate) country: Option<String>,
    pub(crate) limit: Option<Limit>,
    pub(crate) offset: Option<u32>,
}

impl<F: AuthFlow, V: Verifier> Builder<'_, F, V, CategoryPlaylistsEndpoint> {
    #[doc = include_str!("../docs/country.md")]
    pub fn country(mut self, country: impl Into<String>) -> Self {
        self.endpoint.country = Some(country.into());
        self
    }

    #[doc = include_str!("../docs/limit.md")]
    pub fn limit(mut self, limit: u32) -> Self {
        self.endpoint.limit = Some(Limit::new(limit));
        self
    }

    #[doc = include_str!("../docs/offset.md")]
    pub fn offset(mut self, offset: u32) -> Self {
        self.endpoint.offset = Some(offset);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn get(self) -> Result<Page<SimplifiedPlaylist>> {
        self.spotify
            .get(
                format!("/browse/categories/{}/playlists", self.endpoint.id),
                self.endpoint,
            )
            .await
            .map(|p: Playlists| p.playlists)
    }
}