import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Server Application
 *
 */
public class Server {
	public static void main(String[] args){
		if(args.length==1){
			int port=Integer.parseInt(args[0]);
			try {
				ServerSocket serverSocket=new ServerSocket(port);
				int connectedParties=0;
				ClientHandle handle1 = null;
				ClientHandle handle2 = null;
				System.out.println("Message Relay Server Started");
				while(connectedParties!=2){
					Socket clientSocket=serverSocket.accept();
					if(connectedParties==0){//check if it is the first party that is connected
						handle1=new ClientHandle(clientSocket);
						handle1.initIdentifiers();
						connectedParties++;
						System.out.println("Client "+handle1.getSelfIdentifier()+" --> "+handle1.getTargetIdentifier()+ " is CONNECTED");
					}else if(connectedParties==1){//check if it is the second party
						handle2=new ClientHandle(clientSocket);
						handle2.initIdentifiers();
						//check if the target client of first party is this second party
						if(handle1.getTargetIdentifier().equalsIgnoreCase(handle2.getSelfIdentifier()) && handle2.getTargetIdentifier().equalsIgnoreCase(handle1.getSelfIdentifier())){
							System.out.println("Client "+handle2.getSelfIdentifier()+" --> "+handle2.getTargetIdentifier()+ " is CONNECTED");
							connectedParties++;
						}else{
							handle2.close();
							handle2=null;
						}
					}
				}
				
				//if both parties are connected start thread that exchange messages
				Thread exchanger=new Thread(new MessageExchanger(handle1,handle2));
				exchanger.start();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			System.out.println("Usage: java Server severPort");
		}
	}

}

