package com.techcavern.wavetact.commands.utils;

import com.google.gson.JsonObject;
import com.techcavern.wavetact.annot.CMD;
import com.techcavern.wavetact.annot.GenCMD;
import com.techcavern.wavetact.utils.GeneralUtils;
import com.techcavern.wavetact.utils.IRCUtils;
import com.techcavern.wavetact.utils.objects.GenericCommand;
import org.apache.commons.lang3.StringUtils;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.User;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;


public class Google extends GenericCommand {
    @CMD
    @GenCMD

    public Google() {
        super(GeneralUtils.toArray("google goo g"), 0, "google [string to google]" ,"googles something");
    }

    @Override
    public void onCommand(User user, PircBotX Bot, Channel channel, boolean isPrivate, int UserPermLevel, String... args) throws Exception {
        JsonObject results = GeneralUtils.getJsonObject("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + URLEncoder.encode(StringUtils.join(args, " "), "UTF-8")).getAsJsonObject("responseData").getAsJsonArray("results").get(0).getAsJsonObject();
        if (results != null || !results.isJsonNull()) {
            IRCUtils.SendMessage(user, channel, results.get("titleNoFormatting").getAsString() + " - " + results.get("unescapedUrl").getAsString(), isPrivate);
        } else {
            user.send().notice("Search returned no results");
        }
    }
}


@@ -42,16 +42,50 @@
 utils;%0A%0A
+import com.google.gson.JsonArray;%0A
 import c
@@ -111,16 +111,16 @@
 Object;%0A
-
 import c
@@ -357,16 +357,60 @@
 ommand;%0A
+import org.apache.commons.lang3.ArrayUtils;%0A
 import o
@@ -1005,16 +1005,200 @@
 ption %7B%0A
+        int ArrayIndex = 0;%0A        if(GeneralUtils.isInteger(args%5B0%5D))%7B%0A            ArrayIndex = Integer.parseInt(args%5B0%5D)-1;%0A            args = ArrayUtils.remove(args, 0);%0A        %7D%0A
         
@@ -1201,22 +1201,21 @@
     Json
-Object
+Array
  results
@@ -1428,33 +1428,8 @@
 ts%22)
-.get(0).getAsJsonObject()
 ;%0A  
@@ -1440,17 +1440,16 @@
   if
- 
 (results
  != 
@@ -1448,204 +1448,502 @@
 ults
- != null %7C%7C !results.isJsonNull()) %7B%0A            IRCUtils.SendMessage(user, channel, results.get(%22titleNoFormatting%22).getAsString() + %22 - %22 + results.get(%22unescapedUrl%22).getAsString(), isPrivate);
+.size()-1 %3E 0)%7B%0A        if (results.size() %3E= ArrayIndex) %7B%0A            String title = results.get(ArrayIndex).getAsJsonObject().get(%22titleNoFormatting%22).getAsString();%0A            String url = results.get(ArrayIndex).getAsJsonObject().get(%22unescapedUrl%22).getAsString();%0A            IRCUtils.SendMessage(user, channel, title + %22 - %22 + url, isPrivate);%0A        %7Delse%7B%0A            ArrayIndex = ArrayIndex + 1;%0A            user.send().notice(%22Search #%22 + ArrayIndex + %22 does not exist%22);%0A        %7D
 %0A   

Refactor Google Command