package me.despawningbone.discordbot.command.misc;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import me.despawningbone.discordbot.command.Command;
import me.despawningbone.discordbot.command.CommandResult;
import me.despawningbone.discordbot.command.CommandResult.CommandResultType;
import me.despawningbone.discordbot.utils.MiscUtils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;

public class Spoiler extends Command {  //allow people to redirect the spoiler box to another channel?

	public Spoiler() {
		this.desc = "Turns your message into a hover-only spoiler box!";
		this.usage = "[title:] <message>";
		this.examples = Arrays.asList("mario: peach get rescued");
		this.isDisabled = true;
	}

	@Override
	public CommandResult execute(TextChannel channel, User author, Message msg, String[] args) {  //foul word filter?
		if(channel.getGuild().getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)) {
			if (args.length < 1) {
				return new CommandResult(CommandResultType.INVALIDARGS, "Say something -.-");
			}
			channel.deleteMessageById(msg.getId()).queue();
			EmbedBuilder eb = new EmbedBuilder();
			String[] lineSplit = msg.getContentDisplay().split(":", 2);
			String message;
			if(lineSplit.length < 2) {
				message = String.join(" ", args);
			} else {
				message = lineSplit[1];
				try {
					eb.setTitle(lineSplit[0].split(" ", 3)[2]);	
				} catch (IllegalArgumentException e) {
					channel.sendMessage(e.getMessage()).queue(m -> MiscUtils.delayDeleteMessage(m, 5000));
					return new CommandResult(CommandResultType.INVALIDARGS);
				}
			}
			eb.setAuthor(author.getName() + "#" + author.getDiscriminator());
			//eb.setDescription("[Hover me for the spoiler!](https://discordapp.com/channels/" + channel.getGuild().getId() + "/" + channel.getId() + " \"" + lineSplit[1] + "\")");
			try {
				eb.setDescription("[Hover me for the spoiler!](https://hastebin.com/" + pasteToHastebin(message) + ".txt \"" + message + "\")");
			} catch (JSONException | IOException e) {
				return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e));
			}
			eb.setColor(new Color(255, 255, 0));
			eb.setFooter("Click on the link if you cannot see the hover, or are on Discord mobile!", null);
			channel.sendMessageEmbeds(eb.build()).queue();
			return new CommandResult(CommandResultType.SUCCESS);	
		} else {
			return new CommandResult(CommandResultType.FAILURE, "The bot has no permission to delete messages, and making spoiler box with the actual spoilers still visible seems pointless, ain't it? :P");
		}
	}
	
	private String pasteToHastebin(String message) throws IOException {
		URL url = new URL("https://hastebin.com/documents");
		HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
		httpCon.setDoOutput(true);
		httpCon.setRequestMethod("POST");
		httpCon.addRequestProperty("User-Agent", "Mozilla/4.0");
		httpCon.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
		OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
		out.write(message);
		out.close();
		//System.out.print(httpCon.getResponseMessage());
		return new JSONObject(new JSONTokener(httpCon.getInputStream())).getString("key");
	}
}
