/* Author: Jeff Dalton <J.Dalton@ed.ac.uk>
 *    and: Stephen Potter <stephenp@inf.ed.ac.uk>
 * Updated: Tue Jun 20 15:02:30 2006
 * Copyright: (c) 2001-2006 AIAI, University of Edinburgh
 */

package ix.search;

import java.util.*;
import java.io.IOException;
import java.io.*;
import java.net.*;

import javax.swing.JOptionPane;

import ix.icore.*;
import ix.ip2.*;
import ix.util.*;
import ix.util.lisp.*;

import org.jdom.*;
import org.jdom.input.*;

/**
 * Adds a handler action initiates a google search for the content
 * of an AgendaItem. 
 */
public class InternetSearch extends ItemHandler {

    String PROPS_FILE="local-properties/internet-search.props";

    //private Symbol ACTION_SYMBOL_NAME = Symbol.intern("action");

    protected Ip2 ip2;

    public InternetSearch(Ip2 ip2) {
	super("Search the internet");
	this.ip2 = ip2;
    }

    public List getSyntaxList(){
	return (LList)Lisp.readFromString("((?Internet-search-term))");
    }

    public boolean appliesTo(AgendaItem item) {
	// We want this handler to apply to all agenda items (issues and
	// activities, so we simply return true here - other handlers may
	// have more specific truth conditions (usually based on the content
	// of the agenda item in question).
	return true; 
    }

    public void addHandlerActions(AgendaItem item) {
	item.addAction
	    (new HandlerAction.AutomaticWhenBound(item, this));
    }

    public void handle(AgendaItem item) {
	// The handle method specifies what the handler actually does when
	// it is invoked.

	try{
	    // read in local properties:
	    // the name of the browser executable and of the particular search
	    // engine to use are read in from an XML file: this is convenient
	    // in this case, but not necessary.
	    // Note that in this case, the XML file is read anew every time  
	    // the handler is invoked...

	    SAXBuilder builder = new SAXBuilder(); //SAXDriverClass);
	    Document doc = builder.build(PROPS_FILE);
	    Element root = doc.getRootElement(); // should be <properties>

	    String browserExe = root.getChildText("browser-exe");
	    String engineAdd = root.getChildText("engine-address");


    	    (Runtime.getRuntime()).exec(browserExe+" "+engineAdd+URLEncoder.encode("\""+(item.getAbout()).getShortDescription()+"\"","UTF-8"));


	}
	catch (Exception e){
	    Debug.noteln("Handler error : "+e.toString());
	    // Uh, better do something with this exception:
	    JOptionPane.showMessageDialog(null,
					  "Handler problem:\n"+Debug.foldException(e),
					  "Internet Search Handler Error",
					  JOptionPane.ERROR_MESSAGE);
	}   

	// don't do anything to the status in this case; in other cases, we
	// may want to set the status of the item to, say, done (COMPLETE)
	// following invocation of this handler:
	item.setStatus(Status.EXECUTING);

    }


}
