package de.yannicpunktdee.yoshibot.listeners;

import de.yannicpunktdee.yoshibot.command.YoshiCommandContext;
import de.yannicpunktdee.yoshibot.command.commands.PlayCommand;
import de.yannicpunktdee.yoshibot.command.commands.SayCommand;
import de.yannicpunktdee.yoshibot.main.YoshiBot;
import de.yannicpunktdee.yoshibot.utils.Resources;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceJoinEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;

/**
 * Lauscht auf eingehende Nachrichten und leitet diese an die YoshiBot.executeCommand-Methode weiter, falls es sich um
 * ein Kommando handelt.
 *
 * @author Yannic Link
 */
public class DiscordEventListener extends ListenerAdapter {
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onMessageReceived(MessageReceivedEvent event) {
		if (!event.isFromType(ChannelType.TEXT)) return;
		
		if (event.getAuthor().isBot()) return;
		
		boolean inErlaubtemKanal = Arrays.stream(Resources.getRestrict_commands_to_channel())
				.anyMatch(channel -> channel.equalsIgnoreCase(event.getTextChannel().getName()));
		
		if (Resources.getRestrict_commands_to_channel() != null && !inErlaubtemKanal)
			return;
		
		String raw = event.getMessage().getContentRaw().trim();
		
		if (!raw.startsWith(YoshiCommandContext.PREFIX)) return;
		
		YoshiCommandContext context = new YoshiCommandContext(raw, event);
		if (!context.getState().equals(YoshiCommandContext.State.NO_COMMAND)) YoshiBot.executeCommand(context);
	}
	
	@Override
	public void onGuildVoiceJoin(@NotNull GuildVoiceJoinEvent event) {
		super.onGuildVoiceJoin(event);
		
		if (!Resources.isGreetings_and_byebyes_on()) return;
		
		if (event.getMember().getUser().isBot()) return;
		
		String nameToPlay = event.getMember().getNickname();
		nameToPlay = nameToPlay == null ? event.getMember().getUser().getName() : nameToPlay;
		
		PlayCommand.play(
				SayCommand.buildTTSAudio(Resources.getRandomGreeting(nameToPlay)),
				event.getMember().getVoiceState().getChannel());
	}
	
	@Override
	public void onGuildVoiceLeave(@NotNull GuildVoiceLeaveEvent event) {
		super.onGuildVoiceLeave(event);
		
		if (!Resources.isGreetings_and_byebyes_on()) return;
		
		if (event.getMember().getUser().isBot()) return;
		
		String nameToPlay = event.getMember().getNickname();
		nameToPlay = nameToPlay == null ? event.getMember().getUser().getName() : nameToPlay;
		
		PlayCommand.play(
				SayCommand.buildTTSAudio(Resources.getRandomByebye(nameToPlay)),
				event.getChannelLeft());
	}
	
}
