import java.net.*;
import java.io.*;
import cnrg.itx.signal.*;
import cnrg.itx.datax.devices.*;

public class cupsServer extends Thread
{
	ServerSocket recvSock;
	Socket rcvS;
	cups myCups;
	SignalConnection m_sigConn;
	int myPort;
	
	public cupsServer(cups p_Cups)
	{
		myCups = p_Cups;
		try{
			recvSock = new ServerSocket(0, 20);
			myPort = recvSock.getLocalPort();
			printMessage("listening on port-> "+myPort+"\n");
		}
		catch(IOException ioe){
		}
	}
	
	public void run(){
		
		while(true){
			try{
				printMessage("Ready to accept requests...");
				rcvS = recvSock.accept();
			}
			catch (IOException ioe) 
			{
				printMessage("IO exception in accept, quitting server...");
				break;
			}
			try {
				printMessage("Received something...");
				ObjectInputStream s = new ObjectInputStream(new DataInputStream(rcvS.getInputStream()));
				cupsServerPacket csp = (cupsServerPacket) s.readObject();
				switch(csp.type) 
				{
				case cupsServerPacket.WIRETAP:
					m_sigConn = myCups.getSignalConnection();
					ObjectOutputStream o = new ObjectOutputStream(new DataOutputStream(rcvS.getOutputStream()));
					if(m_sigConn == null) 
					{
						o.writeObject(new cupsServerPacket(cupsServerPacket.NOCONNECTION));
						o.flush();
						rcvS.close();
					}
					else 
					{
						o.writeObject(new cupsServerPacket(cupsServerPacket.SENDPROPERTIES));
					}
					break;
				default:
					break;
				}
			}
			catch(IOException ioe)
			{
				continue;
			}
			catch(ClassNotFoundException cnfe) 
			{
				continue;
			}
		}
		System.out.println("DesktopSignalingServer Thread exiting on Port: " + myPort);
	}
	
	private void printMessage(String message) 
	{
		System.out.println("<CUPS server> : " + message);
	}

}
