import java.util.*;

/**
 * A stateless protocol for system properties
 * @pattern Singleton
 */
public class PropertiesProtocol {
	
	private static PropertiesProtocol instance;
	public static String FINAL_MESSAGE = "BYE";
	private Properties properties;
	
	
	// constructor private - singleton
	private PropertiesProtocol () {
		properties = System.getProperties();
	}
	
	/**
	 * returns the single instance of this protocol
	 */
	public static PropertiesProtocol getInstance () {
		if (instance == null) {
			instance = new PropertiesProtocol();
		}
		return instance;
	}
	
	/**
	 * process the client input; returns a string result for the input
	 */
	public String processInput (String input) {
		if (input.equalsIgnoreCase("list")) {
			return listProperties();
		}
		if (input.equalsIgnoreCase(FINAL_MESSAGE)) {
			return FINAL_MESSAGE;
		}
		String value = properties.getProperty(input);
		if (value == null) {
			return "no such property " + input;
		}
		return value;
	}
	
	// returns a String of all properties seperated by a semicolon
	private String listProperties () {
		StringBuffer buffer = new StringBuffer();
		Enumeration enum = properties.keys();
		while (enum.hasMoreElements()) {
			String next = (String)enum.nextElement();
			buffer.append(next);
			buffer.append(";");
		}
		return buffer.toString();
	}
}

