package edu.oregonstate.library.util;

import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;


public class GoogleSpell {
  /*
   Post code based on Java tip from:
   http://www.javaworld.com/javaworld/javatips/jw-javatip34.html
  */

  public String[] GetWords(String words) {
    try {
      URL                 url;
      URLConnection       urlConn;
      OutputStreamWriter  printout;
      BufferedReader      input;
      String[] 		  gwords;
      int		  x=0;
      url = new URL ( "https://www.google.com/tbproxy/spell?lang=en");

      //Split words to see how many dims should be setup.
      String[] tmp = words.split(" ");
      gwords = new String[tmp.length];
     
      for (int lindex = 0; lindex<tmp.length; lindex++) { 
        // URL connection channel.
        urlConn = url.openConnection();
        urlConn.setDoInput (true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput (true);
        urlConn.setUseCaches (false);
      
        // Specify the content type.
        urlConn.setRequestProperty
        ("Content-Type", "application/x-www-form-urlencoded");
        // Send POST output.
        printout = new OutputStreamWriter ( urlConn.getOutputStream() );
        printout.write ("<spellrequest textalreadyclipped=\"0\" ignoredups=\"1\" ignoredigits=\"1\" ignoreallcaps=\"0\"><text>" + tmp[lindex] + "</text></spellrequest>");
        printout.flush ();
        printout.close ();
     
        // Get response data.
        input = new BufferedReader (new InputStreamReader(urlConn.getInputStream ()));
        // build a string containing the response
        String str;
        String html = "";
        while (null != ((str = input.readLine())))
          html += str;
        // close the stream
        input.close ();
        if (html != "") {
           InputSource inputsource = new InputSource(new StringReader(html));
           XPath xpath = XPathFactory.newInstance().newXPath();
           String exp = "//*";
           NodeList results = (NodeList) xpath.evaluate(exp,inputsource,XPathConstants.NODESET);
	   int length = results.getLength();
           for (int i = 0; i < length; i++) {
	      Node node = results.item(i);
	      if (node instanceof Element) {
               Element e = (Element) node;
	       if (e.getFirstChild()!=null && e.getFirstChild().getNodeValue()!=null) {	
		 if (e!=null) {
	           gwords[x] = e.getFirstChild().getNodeValue();
		   x++;
		 }
	       }
              }
              else {
	       //This should never be called, but just in case the 
	       //element gets evaluated as a node.
               gwords[x] = node.getNodeValue();
	       x++;
	      }
	    }
         } else {gwords[x]=""; x++;}
       }
       return gwords;
    }catch(Exception e) {
        return null;
    }
  }
}

