/************************************************
* Columbia University CS Department
* Systems and Security Group
*
* Open and Survivable Embedded Systems (OASES)
*
* Michael E. Locasto
*
* Protocol For Code Exchange
*  in Survivable Embedded Systems (PCXSES)
*
* This software is provided as is without any
* warranty or guarantee of merchantibility
* or fitness for a particular purpose. This
* software is released under the terms of the
* GNU General Public License (GPL).
*
* Last updated: November 6, 2002
*
***********************************************/


package locasto.pcxses.client;


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

import locasto.logging.Logger;
import locasto.pcxses.protocol.*;

/**
 * Create and send HELLO Bottles. Pull the current state
 * from the pcxClient_Impl.
*
* @author locasto@cs.columbia.edu
*/
final class HelloTask extends TimerTask{


	private String clientName;
	private int acPort = PCXClient.DEFAULT_PORT;
	private String acIP="127.0.0.1";
	private InetAddress acInetAddress;

	private Logger logger;
	private DefaultPCXClient_Impl pcxClient_Impl;
	private Socket client;
	private ObjectOutputStream oout;
	private ObjectInputStream oin;
	private Bottle bottle;


	/** package visible constructor */
	HelloTask( DefaultPCXClient_Impl dp, Logger l, String clientName, String acIP, int acPort ) throws UnknownHostException{
		this.pcxClient_Impl = dp;
		this.logger = l;
		this.clientName = clientName;
		this.acIP = acIP;
		this.acInetAddress = InetAddress.getByName( acIP );
		this.acPort = acPort;
		bottle = new Bottle( Bottle.HELLO_MESSAGE );
		bottle.setClientName( this.clientName );
	}


	public void run(){

		try{

			client = new Socket( acInetAddress, acPort );
			//XXX client.setReuseAddress( true ); ????
			oout = new ObjectOutputStream( client.getOutputStream() );
			oout.flush();

			oin = new ObjectInputStream( client.getInputStream() );

			//pull state from pcxClient_Impl and set it in bottle
			bottle.setState( pcxClient_Impl.getCurrentState() );

			oout.writeObject( bottle );

		}catch( Exception e ){
			if( logger!=null )
				logger.log( "Problem writing HELLO MESSAGE out is: "+e.getMessage() );
		}finally{
			try{
				if( oout!=null ){
					oout.flush();
					oout.close();
				}
				if( oin!=null )
					oin.close();
				if( client!=null && !client.isClosed() )
					client.close();
			}catch( Exception ee ){
				client=null;
				oout=null;
				oin=null;
			}
		}


	}


}
