import java.net.*;
import java.io.*;

/**
 * A Server that responds to client queries about the server' system properties
 */
public class PropertiesServer {
	
	private static final int PORT = 4444;
	
	public static void main(String[] arg) {
		
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(PORT);
		} catch (IOException e) {
			System.err.println("could not connect server");
			e.printStackTrace();
		}
		Socket connection = null;
		while(true) {
			try {
				// for every client accepted handle conversation in a new thread
				connection = serverSocket.accept();
				new Thread(new PropertiesTask(connection)).start();
			}catch (IOException ioe) {
				System.err.println(ioe);
				System.exit(1);
			}
		}
	}
}

// this class handles the task of a conversation with a single client
class PropertiesTask implements Runnable {
	
	private Socket connection;
	
	/**
	 * Constructs a PropertiesTask for the given Socket connection
	 */
	public PropertiesTask (Socket connection) {
		this.connection = connection;
	}
	
	/**
	 * performs the conversation with the client untill the server sends a BYE. message
	 */
	
	public void run(){
		try {
			BufferedReader in = new BufferedReader(
				new InputStreamReader(connection.getInputStream()));
			PrintWriter out = new PrintWriter(new OutputStreamWriter(
				connection.getOutputStream()),true);
			String inputLine, outputLine;
			
			PropertiesProtocol protocol = PropertiesProtocol.getInstance();
			while ((inputLine = in.readLine()) !=null) {
				outputLine = protocol.processInput(inputLine);
				out.println(outputLine);
				if(outputLine.equals(PropertiesProtocol.FINAL_MESSAGE))
					break;
			}
			// close streams and socket
			out.close();
			in.close();
			connection.close();
		}catch(IOException e) {
			System.out.println(e);
		}
	}
}

