package fr.Skydust.JdrBot.cmds.playmusic;

import fr.Skydust.JdrBot.bases.command.Command;
import fr.Skydust.JdrBot.bases.command.CommandSpec;
import fr.Skydust.JdrBot.cmds.record.Record;
import fr.Skydust.JdrBot.jukebox.JukeboxSystem;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;

@CommandSpec(
        name = "stopmusic|sm",
        description = "(Admin) Arrete le jukebox et supprime son message"
)
public class StopMusic extends Command {
    @Override
    public void call(MessageReceivedEvent e) {
        if(!e.getGuild().getAudioManager().isConnected() || !e.getMember().hasPermission(Permission.ADMINISTRATOR)) {
            return;
        }

        stopMusic(e.getGuild());
    }


    public static void onGuildVoiceUpdate(GuildVoiceUpdateEvent e) {
        if(e.getChannelLeft() != null) {
            if (e.getGuild().getAudioManager().isConnected() && e.getChannelLeft().getIdLong() == e.getGuild().getAudioManager().getConnectedChannel().getIdLong() && e.getChannelLeft().getMembers().size() == 1) {
                stopMusic(e.getGuild());
            }
        }
    }

    public static void stopMusic(Guild g) {
        JukeboxSystem jukebox = PlayMusic.getGuildsJukebox(g);

        // Deletes the jukebox message
        if(jukebox != null) {
            jukebox.jukeboxMessage.delete().queue();
        }

        // Clears the guild's jukebox system
        PlayMusic.jukeboxSystems.put(g.getIdLong(), null);

        // Stops the audio
        PlayMusic.getGuildAudioPlayer(g).scheduler.stop();

        // Leave the voice channel if not recording
        if(!Record.getGuildRecordState(g).isRecording) {
            g.getAudioManager().closeAudioConnection();
        }
    }
}
