package cc.fascinated.bat.service; import cc.fascinated.bat.event.EventListener; import cc.fascinated.bat.model.BatGuild; import cc.fascinated.bat.model.BatUser; import lombok.NonNull; import lombok.extern.log4j.Log4j2; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.Set; /** * @author Fascinated (fascinated7) */ @Service @Log4j2 @DependsOn("discordService") public class EventService extends ListenerAdapter { private final GuildService guildService; private final UserService userService; /** * The list of listeners registered */ public static final Set LISTENERS = new HashSet<>(); @Autowired public EventService(@NonNull GuildService guildService, @NonNull UserService userService, @NonNull ApplicationContext context) { this.guildService = guildService; this.userService = userService; DiscordService.JDA.addEventListener(this); context.getBeansOfType(EventListener.class).values().forEach(this::registerListeners); log.info("Registered {} listeners.", LISTENERS.size()); } /** * Registers an event listener * * @param listener the listener to register */ public void registerListeners(EventListener... listener) { LISTENERS.addAll(Set.of(listener)); } @Override public void onGuildMemberJoin(@NotNull GuildMemberJoinEvent event) { BatGuild guild = guildService.getGuild(event.getGuild().getId()); BatUser user = userService.getUser(event.getUser().getId()); for (EventListener listener : LISTENERS) { listener.onGuildMemberJoin(guild, user, event); } } @Override public void onGuildMemberRemove(@NonNull GuildMemberRemoveEvent event) { BatGuild guild = guildService.getGuild(event.getGuild().getId()); BatUser user = userService.getUser(event.getUser().getId()); for (EventListener listener : LISTENERS) { listener.onGuildMemberLeave(guild, user, event); } } }