package me.despawningbone.discordbot.command.info;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/*import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;*/

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

public class CurrencyConvert extends Command {
	public CurrencyConvert() {
		this.alias = Arrays.asList("currency", "cc");
		this.desc = "convert a currency to another!";
		this.usage = "<from> <to> [amount]";
		this.remarks = Arrays.asList("The currency units use the format of ISO 4217. For the list, see below:", "https://en.wikipedia.org/wiki/ISO_4217");
		this.examples = Arrays.asList("HKD USD", "EUR SGD 100");
	}

	@Override
	public CommandResult execute(TextChannel channel, User author, Message msg, String[] args) {
		String fromc = null;
		String toc = null;
		String num = null;
		try {
			fromc = args[0].toUpperCase();
			toc = args[1].toUpperCase();
		} catch (ArrayIndexOutOfBoundsException e) {
			return new CommandResult(CommandResultType.INVALIDARGS, "Please enter 2 currencies.");
		}
		
		try {  //there is a lot more info, use them too?
			InputStream stream =  new URL("https://query1.finance.yahoo.com/v8/finance/chart/"+ fromc + toc + "=X?range=6h&includePrePost=false&interval=1m").openStream();
			JSONObject main = new JSONObject(new JSONTokener(stream)).getJSONObject("chart").getJSONArray("result").getJSONObject(0);
			double rate = 0;
			try {
				List<Object> close = main.getJSONObject("indicators").getJSONArray("quote").getJSONObject(0).getJSONArray("close").toList();
				close.removeAll(Collections.singleton(null));
				rate = (double) close.get(close.size() - 1);	
			} catch (JSONException e) {
				rate = main.getJSONObject("meta").getDouble("previousClose");
				//rate += new JSONObject(new JSONTokener(new URL("https://query1.finance.yahoo.com/v1/finance/lookup?formatted=true&lang=en-US&region=US&query=" + fromc + toc + "=x&type=all&count=25&start=0&corsDomain=finance.yahoo.com").openStream()))
						//.getJSONObject("finance").getJSONArray("result").getJSONObject(0).getJSONArray("documents").getJSONObject(0).getJSONObject("regularMarketChange").getDouble("raw");
			}
			if(rate == 1) {
				//throw new NullPointerException("Invalid currency conversion!");
				return new CommandResult(CommandResultType.INVALIDARGS, "Invalid currency conversion!");
			}
			try {
				num = args[2];
			} catch (ArrayIndexOutOfBoundsException e) {
				num = "1";
			}
			double f = rate * Double.parseDouble(num);
			channel.sendMessage(num + " " + fromc.toUpperCase() + " = " + new DecimalFormat("#.####").format(f) + " " + toc.toUpperCase()).queue();
			return new CommandResult(CommandResultType.SUCCESS);
		} catch (IOException e) {
			if(e instanceof FileNotFoundException) {
				return new CommandResult(CommandResultType.INVALIDARGS, "Invalid currency. See the help for the list of available currencies.");
			} else {
				return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e));
			}
		} catch (NumberFormatException e) {
			return new CommandResult(CommandResultType.INVALIDARGS, "Invalid amount.");
		}
		
		/*SCRAPE DEPRECATED*/
		
		/*try { // again, not pretty good to scrape but thats the only way to get the ever updating yahoo finance data
			Document doc = Jsoup.connect("https://hk.finance.yahoo.com/quote/" + fromc + toc + "=X").get();
			// System.out.println(doc);
			try {
				String rate = doc.select("span[data-reactid=\"35\"]").first().text().replace(",", "");
				// String cc = doc.select("div[data-reactid=\"6\"] h1").first().text().split(" ")[0].replace("/", "");
				// System.out.println(cc);
				if (Double.parseDouble(rate) == 1 //!cc.equals(fromc + toc) ) {
					throw new NullPointerException();
				}
				boolean nonum = false;
				try {
					num = args[2];
				} catch (ArrayIndexOutOfBoundsException e) {
					nonum = true;
					num = "1";
				}
				String finalrate;
				if (!nonum) {
					double tempn = Double.parseDouble(num);
					double tempr = Double.parseDouble(rate);
					finalrate = String.valueOf(tempn * tempr);
				} else {
					finalrate = rate;
				}
				channel.sendMessage(num + " " + fromc.toUpperCase() + " = " + finalrate + " " + toc.toUpperCase())
						.queue();
				return new CommandResult(CommandResultType.SUCCESS, null);
			} catch (NullPointerException | NumberFormatException e) {
				channel.sendMessage("Invalid currency.").queue();
				return new CommandResult(CommandResultType.INVALIDARGS, null);
			}
		} catch (IOException e) {
			return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e));
		}*/
	}

}
