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 voice_manager = media.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.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.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.playlist_mut().clear();
                        *media.song_mut() = None;

                        return Ok(());
                    }
                };

                // start the next song if possible
                /*
                match self.media.next_callback.borrow().as_ref() {
                    Some(callback) => {
                        *song = Some(handler.play_returning_and_callback(source, callback.clone()));
                        let song_name = self.media.name_mut()?;
                        *song_name.borrow_mut() = first.name.clone();

                        print_error!(msg
                            .channel_id
                            .say(format!("Skipped current song, now playing: {}", first.name)));
                    }
                    None => println!("error getting callback from media"),
                }
                */
                *media.song_mut() = Some(handler.play_returning(source));
                *media.song_name_mut() = first.name.clone();

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

    Ok(())
}
