import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
 * This class represents the client at the server side
 *
 */
public class ClientHandle {
	private Socket clientSocket;
	private BufferedReader in; //input stream
	private PrintWriter out; //output stream
	private String selfIdentifier;//identifier of this client
	private String targetIdentifier;//identifier of remote client that this client wants to communicate
	
	public ClientHandle(Socket clientSocket) throws IOException {
		this.clientSocket = clientSocket;
		//initiatlize input/output streams
		this.in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		this.out=new PrintWriter(clientSocket.getOutputStream(), true);
	}
	/**
	 * Reads in and returns the next message from the stream
	 * If there is no message returns null
	 * @return
	 * @throws IOException
	 */
	public String getNextMessage() throws IOException{
		if(in.ready()){
			return in.readLine();
		}else{
			return null;
		}
	}
	public void sendNextMessage(String msg){
		out.println(msg);
		out.flush();
	}
	public String getSelfIdentifier(){
		return this.selfIdentifier;
	}
	public String getTargetIdentifier(){
		return this.targetIdentifier;
	}
	/**
	 * After the client opens active socket
	 * it sends its identifier(selfIdentifier) and the identifier
	 * that it wants to communicate with(targetIdentifier)
	 * @throws IOException 
	 */
	public void initIdentifiers() throws IOException{
		acquireSelfIdentifier();
		acquireTargetIdentifier();		
	}
	/**
	 * Obtains identifier of the client
	 * @throws IOException 
	 */
	private void acquireSelfIdentifier() throws IOException{
		this.selfIdentifier=in.readLine().trim();
		
	}
	/**
	 * Obtains identifier of the target client that this client
	 * wants to communicate
	 * @throws IOException 
	 */
	private void acquireTargetIdentifier() throws IOException{
		this.targetIdentifier=in.readLine().trim();
	}
	public void close(){
		try {
			in.close();
			out.close();
			clientSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
