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

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

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

    let mut output = String::new();

    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 playlist = media_lock.playlist();

    output += &format!(
        "{} {} queued\n",
        playlist.len(),
        if playlist.len() == 1 { "song" } else { "songs" }
    );

    let max_output = 5;

    for (i, song) in playlist.iter().enumerate() {
        if i < max_output {
            output += &format!("\t{}.\t{}\n", i + 1, song.name.clone());
        } else {
            output += &format!("\t... and {} more", playlist.len() - max_output);
            break;
        }
    }

    msg.channel_id.say(&ctx.http, output)?;

    Ok(())
}
