/* ***************************************************************************+
 * ITX package (cnrg.itx) for telephony application programming.              *
 * Copyright (c) 1999  Cornell University, Ithaca NY.                         *
 * A copy of the license is distributed with this package.  Look in the docs  *
 * directory, filename GPL.  Contact information: bergmark@cs.cornell.edu     *
 ******************************************************************************/

package cnrg.itx.signal;

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

import cnrg.itx.signal.SignalEvent.*;

/**
 * This class is the server thread in all DesktopSignaling components.  
 * The server spawns a new thread to handle each new request.  It can
 * choose its own port, or be told what port to listen on.
 */
class DesktopSignalingServer extends Thread
{	
	/** Listening Socket **/
	private ServerSocket recvSock = null;
	/** Listening port **/
	private int myPort = -1;
	/** Accepting Socket **/
	private Socket rcvS = null;
	/** Number of requests served **/
	private int rNum = 0;
	/** SigPacketHandler handle **/
	private SigPacketHandler mySPH = null;	
	/** DesktopSignaling handle **/
	private DesktopSignaling myDS = null;
	/** To run or not to run **/
	private boolean flag = true;
	private boolean useSIP = false;

	public DesktopSignalingServer(DesktopSignaling ds){
	   this(ds,0);
	}
	
	public DesktopSignalingServer(DesktopSignaling ds, boolean ifSIP)
	{
		this(ds,0);
		useSIP = ifSIP;
	}

	public DesktopSignalingServer(DesktopSignaling ds, int port) {
		myDS = ds;
		try{
			recvSock = new ServerSocket(port, 20);
			myPort = recvSock.getLocalPort();
			myDS.setServerPort(myPort);	
			System.out.println("DesktopSignalingServer listening on port-> "+myPort+"\n");
		}
		catch(IOException ioe){
		System.out.println("DesktopSignalingServer failed to open " +
		" a socket");
		}
	}
	
	/**
	 * Method called when the thread is started.
	 * 
	 * @param   None.
	 * @return  void
	 */
	public void run(){
		
		while(flag){
			try{
				System.out.println("Ready to accept requests...");
				rcvS = recvSock.accept();
				rcvS.setSoTimeout(myDS.TIMEOUT);

				System.out.println("Received something...");
				rNum++;
				mySPH = new SigPacketHandler(rcvS, rNum, myDS, useSIP);
				mySPH.start();										
			}
			catch (SocketException se){
			}
			catch(IOException ioe){
			}
		}
		System.out.println("DesktopSignalingServer Thread exiting on Port: " + myPort);
	}
	
	/**
	 * This method kills the Server thread by closing the listening socket 
	 * and exiting the run() method.  If the socket is already closed,
	 * this tends to hang on the recvSock.close
	 * 
	 * @param   None.
	 * @return  void
	 */
	public void killServer(){
		flag = false;
		try{
		System.out.println("killServer is closing the socket...");
			recvSock.close();
		System.out.println("socket closed.");
		}
		catch(IOException ioe){
			System.out.println("DesktopSignalingServer thread shut down by the user...");
		}
	}
}
