use log::{warn, info, error};
use serenity::async_trait;
use serenity::model::application::interaction::Interaction;
use serenity::model::gateway::Ready;
use serenity::model::channel::Message;
use serenity::prelude::*;

use crate::storage::guilds::InsertGuild;

use super::commands;
use super::commands::audio::create_response;

pub struct Handler {
  // Open AI Config
  pub oai: Option<commands::oai::OAI>
}

#[async_trait]
impl EventHandler for Handler {
  async fn message(&self, ctx: Context, msg: Message) {
    // Ignore messages from bots
    if msg.author.bot {
      return;
    }
    match &self.oai {
      Some(oai) => {
        match msg.mentions_me(&ctx.http).await {
          Ok(mentioned) => {
            let bot_in_thread = match msg.channel_id.get_thread_members(&ctx.http).await {
              Ok(t) => {
                match t.iter().find(|t| t.user_id.unwrap().0 == ctx.cache.current_user_id().0) {
                  Some(_) => true,
                  None => false
                }
              }
              Err(_) => false
            };
            if mentioned || bot_in_thread {
              commands::oai::generate_response(&ctx, &msg, oai).await;
            }
          }
          Err(why) => warn!("Could not check mentions: {:?}", why)
        };
      }
      None => {}
    }
  }

  async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
    if let Interaction::ApplicationCommand(command) = interaction {
      match command.data.name.as_str() {
        "play" => commands::audio::play::run(&ctx, &command).await,
        "stop" => commands::audio::stop::run(&ctx, &command).await,
        "pause" => commands::audio::pause::run(&ctx, &command).await,
        "resume" => commands::audio::resume::run(&ctx, &command).await,
        "skip" => commands::audio::skip::run(&ctx, &command).await,
        "volume" => commands::audio::volume::run(&ctx, &command).await,
        _ => {
          let content: String = match command.data.name.as_str() {
            "ping" => commands::ping::run(&command.data.options),
            _ => "Unknown command".to_string()
          };
    
          if let Err(why) = create_response(&ctx, &command, content).await {
            warn!("Cannot respond to slash command: {}", why);
          }
        }
      }
    }
  }

  async fn ready(&self, ctx: Context, ready: Ready) {
    if ready.guilds.is_empty() {
      warn!("No ready guilds found");
    }
    for guild in ready.guilds {
      let _ = InsertGuild::insert(InsertGuild {
        id: (guild.id.0 as i64),
        bot_id: ctx.cache.current_user().id.0 as i64,
        volume: 100
      });
      let commands = guild.id.set_application_commands(&ctx.http, |commands| {
        commands.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::ping::register(command) })
          .create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(command) })
          .create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::stop::register(command) })
          .create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::pause::register(command) })
          .create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::resume::register(command) })
          .create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::skip::register(command) })
          .create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::volume::register(command) })
      }).await;
      match commands {
        Ok(c) => info!("Registered {} commands for guild {}", c.len(), guild.id.0),
        Err(why) => error!("Could not register commands for guild {}: {:?}", guild.id.0, why)
      };
    }
  }
}