use serenity;

use std::fs;

use super::super::prelude::*;

use rusqlite::params;

use serenity::prelude::*;
use serenity::{
    framework::standard::{macros::command, Args, CommandResult},
    model::channel::Message,
};

#[command]
fn remove(ctx: &mut Context, msg: &Message, _: Args) -> CommandResult {
    let data = ctx.data.read();
    let media = match data.get::<Media>() {
        Some(media) => media,
        None => {
            msg.channel_id.say(&ctx.http, "could not find media data")?;
            return Ok(());
        }
    };

    let media_lock = media.lock().unwrap();

    let song_name = media_lock.song_name();
    let sql = media_lock.db();

    // check all tables for this entry
    let mut stmt = match sql.prepare("SELECT name FROM sqlite_master WHERE type='table'") {
        Ok(statement) => statement,
        Err(_) => {
            return Err(serenity::framework::standard::CommandError(
                "failed preparing data base access".to_string(),
            ))
        }
    };

    let rows = match stmt.query_map(params![], |row| row.get(0) as rusqlite::Result<String>) {
        Ok(rows) => rows,
        Err(_) => {
            return Err(serenity::framework::standard::CommandError(
                "failed querying rows".to_string(),
            ))
        }
    };

    // delete song from all tables
    for row in rows {
        let table_name = match row {
            Ok(name) => name,
            Err(_) => {
                return Err(serenity::framework::standard::CommandError(
                    "failed getting name from row".to_string(),
                ))
            }
        };

        if let Err(_) = sql.execute(
            &format!("DELETE FROM {} WHERE name = ?", table_name),
            params![song_name],
        ) {
            return Err(serenity::framework::standard::CommandError(
                "failed executing sql delete".to_string(),
            ));
        }
    }

    if !song_name.is_empty() {
        match fs::remove_file(&song_name) {
            Ok(_) => msg.channel_id.say(
                &ctx.http,
                format!("Remove current song ({}) from local disk", song_name),
            )?,
            Err(err) => msg.channel_id.say(
                &ctx.http,
                format!("Error removing file ({}): {:?}", song_name, err.kind()),
            )?,
        };
    }

    Ok(())
}
