package examples.example5_chat_OO_library;

import javax.swing.JOptionPane;

import simpleNetworking.Client;
import simpleNetworking.MultiServer;
import simpleNetworking.Server;

/**
 * TODO Put here a description of what this class does.
 *
* @author David Mutchler, based on the Java Tutorials on networking. May, 2009.
 */
public class Main {

	/**
	 * Asks the user whether she wishes to be the Server or a Client
	 * (there are two, indistinguishable Clients),
	 * and constructs whichever she requests.
	 *
	 * @param commandLineArguments Ignored here
	 */
	public static void main(String[] commandLineArguments) {
		try {
			String[] options = {"Server", "One of the two Clients"};
			int answer = JOptionPane.showOptionDialog(
					null,
					"Are you the Server or one of the two Clients?\n\n"
						+ "Remember to start the Server before the Clients.\n\n",
						"Which are you -- Server or one of the two Clients?",
					JOptionPane.YES_NO_OPTION,
					JOptionPane.QUESTION_MESSAGE,
					null,
					options,
					"Server");
			
			if (answer == 0) {
				MultiServer multiServer = new MultiServer();
				
				Server server = multiServer.getServer(2);
				multiServer.stop();	// Don't need the multiServer any longer,
									// since we now have the two Clients we need.
				
				new ServerRunner(server);

			} else {
				String hostName = JOptionPane.showInputDialog(
						"OK, you are one of the two Clients.\n\n"
						+ "What is the HostName (e.g. mutchler-3.rose-hulman.edu)\n"
						+ "or IP address (e.g. 137.112.40.1) of the Server?\n"
						+ "(Use     localhost     [or just press OK]    for the computer that this is running on.)\n\n");
				
				Client client = new Client(hostName);
				
				new ChatFrame(client);
			}
		} catch (Exception exception) {	// Something went wrong, e.g.
					// -- the hostname given does not exist, or
			        // -- can't create the Socket(s) because you aren't on the Internet, or
					// -- can't create the Socket(s) because the firewall
			        //    blocks the chosen port, or
					// -- the Client was created before the Server, or
					// -- there was a read or write error,
					//    maybe because the human aborted the Server or Client
			        //    on one computer without telling the Client or Server
			        //    on the other computer, or
			        // -- other possibilities too.
			        // A better program would identify and state the exact source
			        // of the error.
			exception.printStackTrace();
		}
	}
}