package me.despawningbone.discordbot.command.anime;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

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.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;

public class AnimePic extends Command {
	
	public AnimePic() {
		this.desc = "Get anime pics!";
		this.usage = "[search words] [-f] [| index]";
		this.remarks = Arrays.asList("Leave the search words blank for a random pic!", "If you have not specified the index, it will be a random result from the search.", "Include `-f` if you want to load the full picture!", "However, full pictures takes a while to load in.");
		this.alias = Arrays.asList("apic");
		this.examples = Arrays.asList("ryuZU -f", "neptune | 2");
	}
	
	//TODO migrate to another more popular image board?
	
	@Override
	public CommandResult execute(TextChannel channel, User author, Message msg, String[] args) {
		Connection con = null;
		channel.sendTyping().queue();
		
		//full res option
		boolean full = false;
		ArrayList<String> amend = new ArrayList<>(Arrays.asList(args));
		if(amend.contains("-f")) {
			amend.remove("-f");
			full = true;
		}
		
		//random, use most popular last 3 months as order - should return better results
		if(amend.size() < 1) {
			con = Jsoup.connect("https://www.zerochan.net/?s=fav&t=2p=" + (ThreadLocalRandom.current().nextInt(1000) + 1));
		}
		
		String stripped = String.join(" ", amend); 
		String search; int index;
		if(stripped.contains("|")) {
			String[] split = stripped.split(" \\|");
			search = split[0];
			try {
				index = Integer.parseInt(split[1].trim()) - 1;	
			} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
				return new CommandResult(CommandResultType.INVALIDARGS, "Invalid index inputted");
			}
		} else {
			search = stripped;
			index = -1;
		}
		
		try {
			if(con == null) con = Jsoup.connect("https://www.zerochan.net/search?q=" + URLEncoder.encode(search, "UTF-8")).ignoreHttpErrors(true).followRedirects(true); 
			Document document = con.get();
			Element href = document.body();
			Elements resList = null;
			try {
				resList = href.select("ul[id=\"thumbs2\"]").get(0).select("li");
				if (resList.size() == 0) throw new IndexOutOfBoundsException();
				if (resList.size() < index) throw new IndexOutOfBoundsException();
			} catch (IndexOutOfBoundsException e) {
				if(!href.select("ul[id=\"children\"]").isEmpty()) return new CommandResult(CommandResultType.FAILURE, "You need to specify your search words more!");
				else return new CommandResult(CommandResultType.NORESULT);
			}
			
			Element a = resList.get(index == -1 ? ThreadLocalRandom.current().nextInt(resList.size()) : index).select("a").first();
			if(a.hasAttr("rel")) {
				return new CommandResult(CommandResultType.FAILURE, "This picture is not public!");
			}
			
			
			EmbedBuilder eb = new EmbedBuilder();
			eb.setTitle((index == -1 ? "Random" : MiscUtils.ordinal(index + 1)) + (search.isEmpty() ? " anime pic" : " pic for " + search), a.absUrl("href"));
			
			//fetch img - seems like discord shrinks the full image anyways nowadays, is -f really useful anymore lol
			String imgName = a.nextElementSibling().child(0).attr("href").replace("+", ".");  //spaces are represented as dots in the cdn for some reason
			String imgPrefix = a.attr("href").substring(1);  //remove prefix /
			String img = full ?
					"https://static.zerochan.net" + imgName + ".full." + imgPrefix + ".jpg":
					"https://s1.zerochan.net" + imgName + ".600." + imgPrefix + ".jpg";
			eb.setImage(img);
			
			eb.setFooter(full ? "The image might need a while to load in." : "Include -f if you want the full resolution!", null);
			channel.sendMessageEmbeds(eb.build()).queue();
			return new CommandResult(CommandResultType.SUCCESS);
		} catch (IOException e) {
			return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e));
		}
	}
}
