import java.io.IOException;

/**
 * Class responsible to exchange messages between two parties
 *
 */
public class MessageExchanger implements Runnable{
	private ClientHandle party1;
	private ClientHandle party2;
	
	
	public MessageExchanger(ClientHandle party1, ClientHandle party2) {
		this.party1 = party1;
		this.party2 = party2;
	}


	public void run() {
		System.out.println("Message Exchanger Started to Run");
		while(true){
			try {
				exchangeMessages();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * Exchanges a message from party1->party2 and from party2->party1
	 * If both parties have no message returns false, otherwise true
	 * @return
	 * @throws IOException 
	 */
	public boolean exchangeMessages() throws IOException{
		boolean success=false;		
		String msg;
		//first from party1->party2
		msg=party1.getNextMessage();	
		if(msg!=null){
			success=true;
			if(party2!=null){
				//System.out.println("Relaying \""+msg+"\" to "+party2.getSelfIdentifier());
				party2.sendNextMessage(msg);
			}
		}
		//then from party2->party1
		msg=party2.getNextMessage();
		if(msg!=null){
			success=true;
			if(party1!=null){
				//System.out.println("Relaying \""+msg+"\" to "+party1.getSelfIdentifier());
				party1.sendNextMessage(msg);
			}
		}
		return success;		
	}


}

