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 song_name = media.song_name();
    let sql = media.db();

    if let Err(_) = sql.execute("DELETE FROM Vulva3 WHERE 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(())
}
