use super::{
    Database, DatabaseError,
    entities::{ContinueWatchingEpisode, Episode, EpisodeWithLibrary, FileRow, IdRow, NewEpisode},
    queries,
};
use chrono::Utc;
use rusqlite::params;

#[allow(dead_code)]
impl Database {
    db_query_all!(fn find_episodes_by_season(season_id: i64) -> Vec<Episode>, queries::find_episodes_by_season);
    db_query_all!(fn find_episodes_with_library_by_season(season_id: i64) -> Vec<EpisodeWithLibrary>, queries::find_episodes_with_library_by_season);
    db_query_all!(fn find_continue_watching_episodes() -> Vec<ContinueWatchingEpisode>, queries::find_continue_watching_episodes);
    db_query_opt!(fn find_next_queueable_episode(episode_id: i64) -> Option<IdRow>, queries::find_next_queueable_episode);

    db_exec!(fn update_episode_tmdb(tmdb_id: i64, title: &str, id: i64), queries::update_episode_tmdb);
    db_exec!(fn set_episode_watched(watched: bool, id: i64), queries::set_episode_watched);
    db_exec!(fn update_episode_playback(position: f64, id: i64), queries::update_episode_playback);
    db_exec!(fn clear_episode_playback(id: i64), queries::clear_episode_playback);
    db_exec!(fn clear_episodes_playback_by_season(season_id: i64), queries::clear_episodes_playback_by_season);
    db_exec!(fn clear_episodes_playback_by_show(show_id: i64), queries::clear_episodes_playback_by_show);
    //db_exec!(fn set_episodes_watched_by_season(season_id: i64, watched: bool), queries::set_episodes_watched_by_season);
    //db_exec!(fn set_episodes_watched_by_show(show_id: i64, watched: bool), queries::set_episodes_watched_by_show);

    pub fn create_episode(&mut self, new_episode: NewEpisode) -> Result<i64, DatabaseError> {
        let now = Utc::now();
        let (_, insert_id) = self.exec_cmd(
            &queries::create_episode,
            params![
                new_episode.season_id,
                new_episode.library_id,
                Option::<i64>::None,
                new_episode.episode_number,
                Option::<String>::None,
                new_episode.file,
                now,
                now
            ],
        )?;

        Ok(insert_id)
    }

    pub fn find_episode_files_by_library(
        &mut self,
        library_id: i64,
    ) -> Result<Vec<String>, DatabaseError> {
        let rows: Vec<FileRow> =
            self.query_all(&queries::find_episode_files_by_library, [library_id])?;
        Ok(rows.into_iter().map(|r| r.file).collect())
    }
}
