package fr.Skydust.JdrBot.cmds.record;

import java.util.Date;
import java.util.HashMap;

import fr.Skydust.JdrBot.audio.handler.JdrBotARH;
import fr.Skydust.JdrBot.bases.command.Command;
import fr.Skydust.JdrBot.bases.command.CommandSpec;
import fr.Skydust.JdrBot.stock.RecordState;
import fr.Skydust.JdrBot.enums.MessageType;
import fr.Skydust.JdrBot.utils.Utils;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;

@CommandSpec(
		name = "record",
		description = "(Admin) Enregistre le chat vocal"
)
public class Record extends Command {
	public static HashMap<Long, RecordState> recordStates = new HashMap<>();

	@Override
    public void call(MessageReceivedEvent e)
    {
    	if(e.getMember().hasPermission(Permission.ADMINISTRATOR)) {
			RecordState currentRS = getGuildRecordState(e.getGuild());

			if (currentRS.isProcessing) {
				Utils.sendMessage(e.getChannel(), MessageType.ERROR, "Un enregistrement est en cours de finalisation");
				return;
			}
			if (currentRS.isRecording) {
				Utils.sendMessage(e.getChannel(), MessageType.ERROR, "Un enregistrement est déjà en cours");
				return;
			}

			if (e.getMember().getVoiceState().getChannel() != null) {
				Utils.sendMessage(e.getChannel(), MessageType.NORMAL, "Lancement d'un enregistrement par " + e.getAuthor().getAsMention() + "\n`!stoprecord` pour le terminer\n`!crecord` pour annuler");

				System.out.println("[" + new Date() + "] Le serveur ID " + e.getGuild().getId() + "(" + e.getGuild().getName() + ") vient de lancer un enregistrement");

				e.getGuild().getAudioManager().openAudioConnection(e.getMember().getVoiceState().getChannel());

				currentRS.newRecord();
				currentRS.isRecording = true;
			} else {
				Utils.sendMessage(e.getChannel(), MessageType.ERROR, "Vous n'êtes pas dans un salon vocal");
			}
		}
    }

	public static synchronized RecordState getGuildRecordState(Guild guild) {
		long guildId = Long.parseLong(guild.getId());
		RecordState recordState = recordStates.get(guildId);

		if (recordState == null) {
			recordState = new RecordState();
			recordStates.put(guildId, recordState);

			guild.getAudioManager().setReceivingHandler(new JdrBotARH(recordState));
		}

		return recordState;
	}
}