/* 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 SendToRobot extends ItemHandler{

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

    public SendToRobot(Ip2 ip2) {
	super("Send to URBI");
	this.ip2 = ip2;
	
	TestIP2 test = new TestIP2(ip2);
	test.run();
    }

    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) {
	// Handle will actually attempt to send command to URBI and once that command is finished
	// URBI will send back and end tag which I-X will read and set the status of the
	// AgendaItem accordingly
	
	item.setStatus(Status.EXECUTING);

	HandleConnection test = new HandleConnection(item);
	new Thread(test).start();

	String testString = "mytag+end: robot.walk(10s);\n";
	try{
		Socket foo = test.returnSocket();
		DataInputStream input = new DataInputStream(foo.getInputStream());
		
	
		DataOutputStream output = test.returnDataOutputStream();
	
		output.writeBytes(testString);
		
		
		//Wait for command to end to tell the Activity that the command has finished 
		String response;
		byte b[] = new byte[2000];
		input.read(b);
		response = new String(b);
		
		System.out.println("Reached Here");
		StringTokenizer tokens = new StringTokenizer(response);

		while (tokens.hasMoreTokens())
		{
			String word = tokens.nextToken();
			if(word.equals("end"))
			{
			   item.setStatus(Status.COMPLETE);
			   break;
			}
		}
			
			
	
		/*
		//Close Thread
		input.close();
		output.close();
		foo.close();
		*/
	}catch(Exception e){
		e.printStackTrace();
	}
	
   }

}



