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
use crate::media::InsertableMedia;
use crate::media::Media;
use crate::media::UpdateMedia;
use crate::user::UserID;
use crate::DatabaseError;

use serde::{Deserialize, Serialize};

/// Episode struct encapsulates a media entry representing a episode
#[derive(Clone, Serialize, Debug)]
pub struct Episode {
    #[serde(skip_serializing)]
    /// Unique id provided by postgres
    pub id: i64,
    /// Season id foreign_key
    pub seasonid: i64,
    /// episode number
    pub episode: i64,

    /// Regerence to a media object which represents this epsiode.
    /// We are essnetially aliasing and wrapping around Media transparently, behind the
    /// scene in the db episode inherits all fields from media.
    #[serde(flatten)]
    pub media: Media,
}

/// This struct is purely used for querying episodes which later gets converted into a Episode
/// struct
#[derive(PartialEq, Debug, Copy, Clone, sqlx::FromRow)]
pub struct EpisodeWrapper {
    pub id: i64,
    pub seasonid: i64,
    pub episode_: i64,
}

impl Episode {
    pub async fn get_first_for_season(
        conn: &mut crate::Transaction<'_>,
        season_id: i64,
    ) -> Result<Self, DatabaseError> {
        let wrapper = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT id as "id!", seasonid, episode_
            FROM episode
            WHERE seasonid = ?
            ORDER BY episode_ ASC"#,
            season_id
        )
        .fetch_one(&mut *conn)
        .await?;

        let ep = Media::get(conn, wrapper.id).await?;

        Ok(wrapper.into_episode(ep))
    }

    pub async fn get_first_for_show(
        conn: &mut crate::Transaction<'_>,
        tv_id: i64,
    ) -> Result<Self, DatabaseError> {
        let wrapper = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT episode.id as "id!", seasonid, episode_
            FROM episode
            INNER JOIN season on season.id = episode.seasonid
            WHERE season.tvshowid = ?
            ORDER BY episode_ ASC, season.season_number ASC
            LIMIT 1"#,
            tv_id
        )
        .fetch_one(&mut *conn)
        .await?;

        let ep = Media::get(conn, wrapper.id).await?;

        Ok(wrapper.into_episode(ep))
    }

    /// Method returns all of the episodes belonging to a tv show.
    ///
    /// # Arguments
    /// * `conn` - a mutable reference to a sqlx transaction.
    /// * `media` - reference to a media object which should be a tv show.
    pub async fn get_all_of_tv(
        conn: &mut crate::Transaction<'_>,
        tv_show_id: i64,
    ) -> Result<Vec<Self>, DatabaseError> {
        let mut episodes = vec![];

        let wrappers = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT episode.id as "id!", episode.episode_, episode.seasonid FROM episode
                INNER JOIN season ON season.id = episode.seasonid
                INNER JOIN tv_show ON tv_show.id = season.tvshowid
                WHERE tv_show.id = ?
                ORDER BY season.season_number, episode.episode_"#,
            tv_show_id
        )
        .fetch_all(&mut *conn)
        .await?;

        for wrapper in wrappers {
            if let Ok(episode) = Media::get(&mut *conn, wrapper.id as i64).await {
                episodes.push(wrapper.into_episode(episode))
            }
        }

        Ok(episodes)
    }

    // FIXME: This function might be especially heavy on the DB.
    /// Method returns all of the episodes belonging to a season.
    ///
    /// # Arguments
    /// * `conn` - mutable reference to a sqlx transaction.
    /// * `media` - reference to a season object/entry.
    pub async fn get_all_of_season(
        conn: &mut crate::Transaction<'_>,
        season_id: i64,
    ) -> Result<Vec<Episode>, DatabaseError> {
        let wrappers = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT id as "id!", episode_, seasonid FROM episode WHERE seasonid = ?"#,
            season_id
        )
        .fetch_all(&mut *conn)
        .await?;

        let mut episodes = vec![];

        for wrapper in wrappers {
            if let Ok(episode) = Media::get(&mut *conn, wrapper.id as i64).await {
                episodes.push(wrapper.into_episode(episode))
            }
        }

        Ok(episodes)
    }

    /// Method returns a episodes discriminated by episode number, season number and tv show id
    ///
    /// # Arguments
    /// * `conn` - mutable reference to a sqlx transaction.
    /// * `id` - The id of a tv show we target
    /// * `season_num` - The season we are targetting
    /// * `ep_num` - Episode we are targetting
    pub async fn get(
        conn: &mut crate::Transaction<'_>,
        tv_id: i64,
        season_num: i64,
        ep_num: i64,
    ) -> Result<Episode, DatabaseError> {
        let wrapper = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT episode.id as "id!", episode.episode_, episode.seasonid  FROM episode
            INNER JOIN season ON season.id = episode.seasonid
            WHERE season.tvshowid = ?
            AND season.season_number = ?
            AND episode.episode_ = ?"#,
            tv_id,
            season_num,
            ep_num
        )
        .fetch_one(&mut *conn)
        .await?;

        let ep = Media::get(conn, wrapper.id as i64).await?;

        Ok(wrapper.into_episode(ep))
    }

    pub async fn get_by_id(
        conn: &mut crate::Transaction<'_>,
        episode_id: i64,
    ) -> Result<Episode, DatabaseError> {
        let wrapper = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT episode.*  FROM episode
            WHERE episode.id = ?"#,
            episode_id
        )
        .fetch_one(&mut *conn)
        .await?;

        let ep = Media::get(conn, wrapper.id as i64).await?;

        Ok(wrapper.into_episode(ep))
    }

    pub async fn get_season_episode_by_id(
        conn: &mut crate::Transaction<'_>,
        episode_id: i64,
    ) -> Result<(i64, i64), DatabaseError> {
        struct Record {
            episode: i64,
            season: i64,
        }

        let result = sqlx::query_as!(
            Record,
            "SELECT episode_ as episode, season.season_number as season FROM episode
            INNER JOIN season ON season.id = episode.seasonid
            WHERE episode.id = ?",
            episode_id
        )
        .fetch_one(&mut *conn)
        .await?;

        Ok((result.season, result.episode))
    }

    pub async fn get_season_number(
        &self,
        conn: &mut crate::Transaction<'_>,
    ) -> Result<i64, DatabaseError> {
        let record = sqlx::query!(
            "SELECT season.season_number FROM season
            WHERE season.id = ?",
            self.seasonid
        )
        .fetch_one(&mut *conn)
        .await?;

        Ok(record.season_number)
    }

    /// Function will query for the episode after the episode passed in.
    pub async fn get_next_episode(
        &self,
        conn: &mut crate::Transaction<'_>,
    ) -> Result<Episode, DatabaseError> {
        let season_number = self.get_season_number(&mut *conn).await?;

        let record = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT episode.id as "id!", episode.seasonid, episode.episode_ FROM episode
            INNER JOIN season ON season.id = episode.seasonid
            WHERE season.tvshowid = (
                SELECT _tblseason.tvshowid FROM _tblseason
                WHERE _tblseason.id = ?
            ) AND ((
                episode.episode_ > ? AND
                season.season_number = ?
            ) OR season.season_number > ?)
            ORDER BY season.season_number, episode.episode_
            LIMIT 1"#,
            self.seasonid,
            self.episode,
            season_number,
            season_number
        )
        .fetch_one(&mut *conn)
        .await?;

        let ep = Media::get(conn, record.id as i64).await?;

        Ok(record.into_episode(ep))
    }

    /// Function will query for the episode after the episode passed in.
    pub async fn get_prev_episode(
        &self,
        conn: &mut crate::Transaction<'_>,
    ) -> Result<Episode, DatabaseError> {
        let season_number = self.get_season_number(&mut *conn).await?;

        let record = sqlx::query_as!(
            EpisodeWrapper,
            r#"SELECT episode.id as "id!", episode.seasonid, episode.episode_ FROM episode
            INNER JOIN season ON season.id = episode.seasonid
            WHERE season.tvshowid = (
                SELECT _tblseason.tvshowid FROM _tblseason
                WHERE _tblseason.id = ?
            ) AND ((
                episode.episode_ < ? AND
                season.season_number = ?
            ) OR season.season_number < ?)
            ORDER BY season.season_number DESC, episode.episode_ DESC
            LIMIT 1"#,
            self.seasonid,
            self.episode,
            season_number,
            season_number
        )
        .fetch_one(&mut *conn)
        .await?;

        let ep = Media::get(conn, record.id as i64).await?;

        Ok(record.into_episode(ep))
    }

    /// Function will query the last episode that was watched for a show.
    pub async fn get_last_watched_episode(
        conn: &mut crate::Transaction<'_>,
        tvid: i64,
        uid: UserID,
    ) -> Result<Option<Episode>, DatabaseError> {
        // FIXME: We're using the query_as function instead of macro because `LEFT OUTER JOIN`
        // crashes the proc macro.
        let result = sqlx::query_as::<_, EpisodeWrapper>(
            "SELECT episode.* FROM episode
            INNER JOIN season ON season.id = episode.seasonid
            INNER JOIN progress ON progress.media_id = episode.id AND progress.user_id = ?
            WHERE season.tvshowid = ?
            ORDER BY progress.populated DESC
            LIMIT 1",
        )
        .bind(uid)
        .bind(tvid)
        .fetch_optional(&mut *conn)
        .await?;

        let result = if let Some(r) = result {
            r
        } else {
            return Ok(None);
        };

        let ep = Media::get(conn, result.id as i64).await?;
        Ok(Some(result.into_episode(ep)))
    }

    /// Method deletes a episode based on the tv show id, season number, and episode number
    ///
    /// # Arguments
    /// * `&` - diesel &ection reference to postgres
    /// * `id` - The id of a tv show we target
    /// * `season_num` - The season we are targetting
    /// * `ep_num` - Episode we are targetting
    pub async fn delete(
        conn: &mut crate::Transaction<'_>,
        episode_id: i64,
    ) -> Result<usize, DatabaseError> {
        // NOTE: no need to manually delete the episode entry from `episode` because of the
        // cascade delete.
        Ok(Media::delete(conn, episode_id).await?)
    }
}

#[derive(Debug)]
pub struct InsertableEpisode {
    pub media: InsertableMedia,
    pub seasonid: i64,
    pub episode: i64,
}

impl InsertableEpisode {
    /// Method inserts a new episode into the database
    ///
    /// # Arguments
    /// * `&` - diesel &ection reference to postgres
    pub async fn insert(&self, conn: &mut crate::Transaction<'_>) -> Result<i64, DatabaseError> {
        if let Some(r) = sqlx::query!(
            r#"SELECT id as "id!" FROM episode WHERE episode.seasonid = ? AND episode.episode_ = ?"#,
            self.seasonid,
            self.episode
        )
        .fetch_optional(&mut *conn)
        .await?
        {
            return Ok(r.id);
        }

        // NOTE: use insert blind here just in case we have conflicts between episode names.
        let media_id = self.media.insert_blind(&mut *conn).await?;
        let result = sqlx::query!(
            "INSERT INTO episode (id, episode_, seasonid)
            VALUES ($1, $2, $3)",
            media_id,
            self.episode,
            self.seasonid
        )
        .execute(&mut *conn)
        .await?
        .last_insert_rowid();

        Ok(result)
    }
}

impl EpisodeWrapper {
    pub fn into_episode(self, media: Media) -> Episode {
        Episode {
            id: self.id,
            seasonid: self.seasonid,
            episode: self.episode_,
            media,
        }
    }
}

#[derive(Deserialize, Default, Debug)]
pub struct UpdateEpisode {
    pub seasonid: Option<i64>,
    pub episode: Option<i64>,

    #[serde(flatten)]
    pub media: UpdateMedia,
}

impl UpdateEpisode {
    /// Method updates the rows of a episode.
    ///
    /// # Arguments
    /// * `&` - diesel &ection reference to postgres
    /// * `id` - id of the episode we wish to update.
    pub async fn update(
        &self,
        conn: &mut crate::Transaction<'_>,
        id: i64,
    ) -> Result<usize, DatabaseError> {
        self.media.update(&mut *conn, id).await?;

        crate::opt_update!(conn,
            "UPDATE episode SET seasonid = ? WHERE id = ?" => (self.seasonid, id),
            "UPDATE episode SET episode_ = ? WHERE id = ?" => (self.episode, id)
        );

        Ok(1)
    }
}