use serenity;
use serenity::voice::ffmpeg;

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

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

#[command]
fn skip(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 data = ctx.data.write();

    if let Some(media) = data.get_mut::<Media>() {
        let mut media_lock = media.lock().unwrap();

        let voice_manager = media_lock.voice_manager.clone();
        let mut manager = voice_manager.lock();

        let guild_id = guild_id(ctx, msg)?;

        if let Some(handler) = handler(guild_id, &mut manager) {
            // if current song is the last song in this playlist, just return
            if media_lock.playlist().is_empty() {
                msg.channel_id
                    .say(&ctx.http, "playlist is empty, no next song available")?;

                return Ok(());
            } else {
                // remove the current song from the playlist
                let first = media_lock.playlist_mut().remove(0);

                // stop the current song from playing
                handler.stop();

                // load next song into memory
                let source = match ffmpeg(first.name.clone()) {
                    Ok(mpeg) => mpeg,
                    Err(_) => {
                        media_lock.playlist_mut().clear();
                        *media_lock.song_mut() = None;

                        return Ok(());
                    }
                };

                *media_lock.song_mut() = Some(handler.play_returning(source));
                *media_lock.song_name_mut() = first.name.clone();

                msg.channel_id.say(
                    &ctx.http,
                    format!("Skipped current song, now playing: {}", first.name),
                )?;
            }
        }
    }

    Ok(())
}
