package de.yannicpunktdee.yoshibot.command.commands;

import de.yannicpunktdee.yoshibot.command.YoshiCommand;
import de.yannicpunktdee.yoshibot.command.YoshiCommandContext;
import de.yannicpunktdee.yoshibot.main.YoshiBot;
import de.yannicpunktdee.yoshibot.utils.Resources;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.VoiceChannel;

import java.awt.*;
import java.io.File;

public class PlayCommand extends YoshiCommand {

	protected String[] requiredArguments = {"name"};

	
	public PlayCommand(YoshiCommandContext context) {
		super(context);
	}


	@Override
	public boolean execute() {
		if (!super.execute()) return false;
		
		if (context.containsArguments(new String[]{"add"})) {
			File download = downloadAttachmentToFile(Resources.getAudioPath(), context.getArgument("name"));
			if(download.isFile()) sendInfoMessage("Audio erfolgreich hinzugefügt.");
			else sendErrorMessage("Audio konnte nicht hinzugefügt werden.");
		} else if (context.containsArguments(new String[]{"list"})) {
			File audioDirectory = new File(Resources.getAudioPath());
			StringBuilder sb = new StringBuilder();
			for (File f : audioDirectory.listFiles()) {
				String fName = f.getName();
				if (!fName.endsWith(".opus")) continue;
				sb.append(fName.substring(0, fName.lastIndexOf(".opus")));
				sb.append("\n");
			}
			EmbedBuilder eb = new EmbedBuilder();
			eb.setTitle("Es sind folgende Audios verf\u00fcgbar:");
			eb.setColor(Color.cyan);
			eb.setDescription(sb.toString());
			sendCustomMessage(eb.build());
		} else {
			File file = new File(Resources.getPathToAudioFile(context.getArgument("name")));
			if(!file.isFile()){
				sendErrorMessage(String.format("Konnte keine Audiodatei namens '%s.opus' finden!",
						context.getArgument("name")));
				return false;
			}
			VoiceChannel vc = getVoiceChannelByParam();
			if(vc == null){
				sendErrorMessage("Konnte keinen Audiochannel auswählen.");
				return false;
			}
			YoshiBot.getInstance().playSound(file, vc);
		}
		
		return true;
	}
	
}
