use log::{debug, error};

use serenity::prelude::*;
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;

use super::{get_songbird, create_response, edit_response};

pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
  // Create the initial response
  if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
    error!("Failed to create response message: {}", why);
    return;
  }

  let guild_id = match command.guild_id {
    Some(g) => g,
    None => {
      if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
        error!("Failed to edit response message: {}", why);
      }
      return;
    }
  };
  let manager = get_songbird(ctx).await;
  if let Some(handler_lock) = manager.get(guild_id) {
    let handler = handler_lock.lock().await;
    if let Err(err) = handler.queue().pause() {
      if let Err(why) = edit_response(&ctx, &command, format!("Failed to pause: {}", err)).await {
        error!("Failed to edit response message: {}", why);
      }
    } else {
      debug!("Paused the track");
      if let Err(why) = edit_response(&ctx, &command, format!("Pausing the track")).await {
        error!("Failed to edit response message: {}", why);
      }
    }
  }
}

pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
  command.name("pause").description("Pause the current track")
}