//Title:       Client
//Version:	   1.0
//Author:      Stuart Lowry
//Company:     Science Applications International Corporation
//Description: Simple client to exercise the usefulness of the StageAgent
//package saic.oaa2;
import com.sri.oaa2.com.*;
import com.sri.oaa2.lib.*;
import com.sri.oaa2.icl.*;
import java.util.*;
import java.io.*;

public class Client
{
	public Client(String[] args)
	{
		try  
		{
			Init(args);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void Init(String[] args) throws Exception
	{
		String userName = System.getProperty("user.name");
		LibOaa oaa = new LibOaa(new LibCom(new LibComTcpProtocol(),args));
		System.out.println("Client starting...");
		if (!oaa.getComLib().comConnect("parent",IclUtils.icl("tcp(A,B)"),
			(IclList)IclUtils.icl("[]")))
		{
			System.out.println("Could not connect to facilitator");
			return;
		}
		if (!oaa.oaaRegister("parent", "client",IclUtils.icl("[]"), (IclList)IclUtils.icl("[]")))
		{
			System.out.println("Could not register");
			return;
		}
		oaa.oaaReady(true);

		/**
	 	* run the actual test...
		*
		* stage(userName,'test.bat',X);
		**/
		System.out.println("Sending request: stage('"+userName+"','test.bat',Ref)");
		String Ref= null,theFile = null;
		IclList answer1 = new IclList();
		IclList answer2 = new IclList();
		IclList answer3 = new IclList();

		if (oaa.oaaSolve(IclUtils.icl("stage('"+userName+"','test.bat',Ref)"), 
			new IclList(), answer1))
		{
			IclTerm response = answer1.iclNthTerm(1);
			Ref = response.iclNthTerm(3).toString();
			System.out.println("Ref= "+ Ref);
		}
		System.out.println("A remote agent can now \"retrieve\" the file as in the following...\n");
		System.out.println("Sending request: unstage('"+userName+"',"+Ref+",File)\n");
		if (oaa.oaaSolve(IclUtils.icl("unstage('" + userName + "',"+ Ref + ",File)"), 
			new IclList(), answer2))
		{
			IclTerm response = answer2.iclNthTerm(1);
			theFile=response.iclNthTerm(3).toString();
			System.out.println("check out the file= "+ theFile+"\n\n\n");
		}

		/**
		* This next bit will cause the StageAgent to exit gracfully.
		* A graceful exit will remove the temporary files.
		* only make this call after you take control of the unstaged file!!
		**/
		
		/*
		System.out.println("Sending shutdown request: shutdown('oaa_StageAgent')\n");
		oaa.oaaSolve(IclUtils.icl("shutdown('oaa_StageAgent')"), 
			new IclList(), answer3);
		*/

		System.exit(0);
	}

	
	public static void main(String[] args)
	{
		new Client(args);
	}

}
