package kr.co.swh.lecture.opensource.project.discode.music;

import java.util.ArrayList;

import kr.co.swh.lecture.opensource.project.youtube.Youtube;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.managers.AudioManager;

public class YoutubeMusicListener extends ListenerAdapter{

	@Override
	public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
		// TODO Auto-generated method stub
		//	super.onGuildMessageReceived(event);
		// Good practise to ignore bots.
		if(event.getAuthor().isBot()) {
			return;
		}
		// Gets the raw message content and binds it to a local variable.
		String message = event.getMessage().getContentRaw().toLowerCase();
		// So we don't have to access event.getChannel() every time.
		TextChannel channel = event.getChannel();
		// Checks if the command is !join.
		if(message.equals("!join")) {
			// Checks if the bot has permissions.
			if(!event.getGuild().getSelfMember().hasPermission(channel, Permission.VOICE_CONNECT)) {
				// The bot does not have permission to join any voice channel. Don't forget the .queue()!
				channel.sendMessage("I do not have permissions to join a voice channel!").queue();
				return;
			}

//			net.dv8tion.jda.api.entities.Member m = event.getMember();
			// Creates a variable equal to the channel that the user is in.
			VoiceChannel connectedChannel = event.getMember().getVoiceState().getChannel();
			// Checks if they are in a channel -- not being in a channel means that the variable = null.
			if(connectedChannel == null) {
				// Don't forget to .queue()!
				channel.sendMessage("You are not connected to a voice channel!").queue();
				return;
			}
			// Gets the audio manager.
			AudioManager audioManager = event.getGuild().getAudioManager();
			// When somebody really needs to chill.
			if(audioManager.isAttemptingToConnect()) {
				channel.sendMessage("The bot is already trying to connect! Enter the chill zone!").queue();
				return;
			}
			// Connects to the channel.
			audioManager.openAudioConnection(connectedChannel);
			// Obviously people do not notice someone/something connecting.
			channel.sendMessage("Connected to the voice channel!").queue();
		} else if(message.equals("!leave")) { // Checks if the command is !leave.
			// Gets the channel in which the bot is currently connected.
            VoiceChannel connectedChannel = event.getGuild().getSelfMember().getVoiceState().getChannel();
            // Checks if the bot is connected to a voice channel.
            if(connectedChannel == null) {
                // Get slightly fed up at the user.
                channel.sendMessage("I am not connected to a voice channel!").queue();
                return;
            }
            // Disconnect from the channel.
            event.getGuild().getAudioManager().closeAudioConnection();
            // Notify the user.
            channel.sendMessage("Disconnected from the voice channel!").queue();
		}

	}
	
	@Override
	public void onMessageReceived(MessageReceivedEvent event) {
		// TODO Auto-generated method stub
		User user = event.getAuthor();
		TextChannel tc = event.getTextChannel();
		Message msg = event.getMessage();
		if(user.isBot()) return;

		String message = msg.getContentRaw();
		if(message.substring(0, 3).equals("!l ")) {
			AudioManager audioManager = event.getGuild().getAudioManager();
			if(!audioManager.isConnected()) {
				VoiceChannel connectedChannel = event.getMember().getVoiceState().getChannel();
				audioManager.openAudioConnection(connectedChannel);
			}
			String title = message.substring(3);
			
			Youtube y = new Youtube();
			ArrayList<String> arr = y.audio(title);
			
			MessageEmbed embed = new EmbedBuilder()
                    .setDescription(arr.get(0))
                    .setTitle(title)
                    .setFooter("swhacademy", null).build();
        	
			tc.sendMessage(title).queue(response -> {
				response.editMessage(embed).queue();
			});;
			
			PlayerManager Playermanager = PlayerManager.getINSTANCE();
			Playermanager.loadAndPlay(tc, arr.get(0));
			Playermanager.getGuildMusicManager(tc.getGuild()).player.setVolume(10);
			
			
//			for(String s : arr) {
//				// Create the EmbedBuilder instance
//				EmbedBuilder eb = new EmbedBuilder();
//
//				/*
//				    Set the title:
//				    1. Arg: title as string
//				    2. Arg: URL as string or could also be null
//				 */
//				eb.setTitle(title, null);
//				eb.setThumbnail("https://swhcoding.com/img/testimonials/person-1.gif");
//				eb.setColor(Color.red);
//				eb.setColor(new Color(0xF40C0C));
//				eb.setColor(new Color(255, 0, 54));
//
//				eb.addField(title, s, false);
////				tc.sendMessage(eb.build()).queue(response /* => Message */ -> {
////
////	        		response.editMessage(s).queue();
////
////	        	});
//				tc.sendMessage(title) /* => RestAction<Message> */
//            	.queue(response /* => Message */ -> {
//
//            		response.editMessage(s).queue();
//
//            	});
//	        }
		}



		//		// 형태소 분석
		//		for (Eojeol eojeol : Analyzer.parseEojeolJava(msg.getContentRaw())) {
		//			for (LNode node : eojeol.nodesJava()) {
		//				Morpheme m = node.morpheme();
		//				tc.sendMessage(m.surface() + " / 품사:" + m.feature().head()).queue();
		//			}
		//		}

		//		EmbedBuilder eb = new EmbedBuilder();
		//		eb.setTitle("It's GIVEAWAY-TIME!");
		//		eb.setDescription("Prize: " + "\n Winners: " + 1);
		//		eb.setColor(Color.BLUE);
		//		eb.setFooter("바닥");

//		// Create the EmbedBuilder instance
//		EmbedBuilder eb = new EmbedBuilder();
//
//		/*
//		    Set the title:
//		    1. Arg: title as string
//		    2. Arg: URL as string or could also be null
//		 */
//		eb.setTitle(m, null);
//		eb.setThumbnail("https://swhcoding.com/img/testimonials/person-1.gif");
//
//		/*
//		    Set the color
//		 */
//		eb.setColor(Color.red);
//		eb.setColor(new Color(0xF40C0C));
//		eb.setColor(new Color(255, 0, 54));
//
//		/*
//		    Set the text of the Embed:
//		    Arg: text as string
//		 */
////		eb.setDescription("Text");
//
//		/*
//		    Add fields to embed:
//		    1. Arg: title as string
//		    2. Arg: text as string
//		    3. Arg: inline mode true / false
//		 */
//		eb.addField("Title of field", "test of field", false);
//
////		/*
////		    Add spacer like field
////		    Arg: inline mode true / false
////		 */
////		eb.addBlankField(false);
//
//		/*
//		    Add embed author:
//		    1. Arg: name as string
//		    2. Arg: url as string (can be null)
//		    3. Arg: icon url as string (can be null)
//		 */
//		//		eb.setAuthor("name", null, "https://github.com/zekroTJA/DiscordBot/blob/master/.websrc/zekroBot_Logo_-_round_small.png");
//
//		/*
//		    Set footer:
//		    1. Arg: text as string
//		    2. icon url as string (can be null)
//		 */
//		//		eb.setFooter("Text", "https://github.com/zekroTJA/DiscordBot/blob/master/.websrc/zekroBot_Logo_-_round_small.png");
//
//		/*
//		    Set image:
//		    Arg: image url as string
//		 */
//		//		eb.setImage("https://github.com/zekroTJA/DiscordBot/blob/master/.websrc/logo%20-%20title.png");
//
//		/*
//		    Set thumbnail image:
//		    Arg: image url as string
//		 */
//		//		eb.setThumbnail("https://github.com/zekroTJA/DiscordBot/blob/master/.websrc/logo%20-%20title.png");
//		event.getTextChannel().sendMessage(eb.build()).queue();

	}

}
