package de.yannicpunktdee.yoshibot.command.commands;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.UUID;

public class SayCommand extends YoshiCommand {
	
	public static String resourceToDelete = null;
	
	
	protected final String[] requiredArguments = {"text", "channel"};
	
	
	public SayCommand(YoshiCommandContext context) {
		super(context);
	}
	
	public static String buildTTSAudio(String text) {
		String path = Resources.getPathToTempAudioFile(UUID.randomUUID().toString());
		
		try {
			ProcessBuilder pb = new ProcessBuilder(
					"python3",
					Resources.getTtsPath(),
					"--text",
					text,
					"--lang",
					"de",
					"--out",
					path);
			
			Process p = pb.start();
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = errorReader.readLine()) != null) {
				builder.append(line).append("\n");
			}
			if (builder.toString().length() > 0) {
				Logger.logError(builder.toString());
			}
			if (resourceToDelete != null)
				synchronized (resourceToDelete) {
					resourceToDelete = path;
				}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		return path;
	}
	
	@Override
	public boolean execute() {
		if (!super.execute()) return false;
		
		String path = buildTTSAudio(context.getArgument("text"));
		
		List<VoiceChannel> channels = YoshiBot.getInstance().jda
				.getVoiceChannelsByName(context.getArgument("channel"), true);
		if (!(channels.size() > 0)) {
			context.getEvent().getTextChannel().sendMessage("Der Kanalname konnte nicht gefunden werden.").queue();
			return false;
		}
		VoiceChannel vc = channels.get(0);
		
		YoshiBot.getInstance().audioPlayerManager.loadItem(path, new AudioLoadResultHandlerImpl());
		vc.getGuild().getAudioManager().openAudioConnection(vc);
		
		return false;
	}
	
}
