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

use rusqlite::params;

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

// This imports `typemap`'s `Key` as `TypeMapKey`.
use serenity::prelude::*;

#[command]
fn tag(ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult {
    if let Err(err) = channel_contains_author(ctx, msg) {
        msg.channel_id.say(&ctx.http, err)?;
        return Ok(());
    }

    let mut data = ctx.data.write();
    let media = match data.get_mut::<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 mut tag = args.single::<String>()?;

    for arg in args.iter::<String>() {
        tag += &format!(" {}", arg?.trim());
    }

    match media_lock.db().execute(
        &format!(
            "CREATE TABLE IF NOT EXISTS {} (
                name    TEXT PRIMARY KEY
            )",
            tag
        ),
        params![],
    ) {
        Ok(_) => (),
        Err(err) => {
            println!("{}", err);
            return Ok(());
        }
    };

    let song_name = media_lock.song_name();

    if media_lock
        .db()
        .execute(
            &format!(
                "INSERT INTO {} (name)
                    VALUES (?1)",
                tag
            ),
            params![song_name],
        )
        .is_err()
    {
        msg.channel_id.say(
            &ctx.http,
            format!("could not add tag ({}) for {}", tag, song_name),
        )?;
    }

    Ok(())
}
