package streams;


import java.awt.Desktop;
import java.io.*;
import java.net.*;
import java.util.*;

/**
 * A class that performs Google searches.
 *
 * Specifically, this class creates a new thread of execution that
 * continuously reads from a DataInputStream.  A Google search is
 * conducted for each line that is read.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Googler implements Runnable
{
    private DataInputStream    in;
    private Desktop            desktop;    
    private Thread             controlThread;

    /**
     * Explicit Value Constructor
     *
     * @param in   The DataInputStream to read from
     */
    public Googler(DataInputStream in)
    {
       this.in = in;
       desktop = Desktop.getDesktop();
    }

    /**
     * The code to execute (required by Runnable).
     */
    public void run()
    {
       String            line;
       URI               uri;

       try
       {
          while ((line = in.readLine()) != null) 
          {
             uri = new URI("http",null,"www.google.com",-1,
                           "/search","q="+line,null);

             desktop.browse(uri); // Returns immediately
          }
       }
       catch (IOException ioe) 
       {
          // Print the complete trace of the exception
          ioe.printStackTrace();
       }
       catch (URISyntaxException use)
       {
          // Print the complete trace of the exception
          use.printStackTrace();           
       }
    }    

    /**
     * Start this Googler (in its own thread of execution).
     */
    public void start()
    {
        if (controlThread == null)
        {
            controlThread = new Thread(this);
            controlThread.start();
        }
    }
}
