package communication.protocols;

import java.util.Iterator;
import java.util.Set;

import communication.messages.HelloReplyMessage;
import communication.messages.HelloType;
import communication.messages.Message;
import data.system.NodeInfo;

public class HelloProtocol implements Protocol {

	private Set<NodeInfo> nodes;
	
	public HelloProtocol(Set<NodeInfo> nodes) {
		this.nodes = nodes;
	}
	
	@Override
	public String getAcceptedMessageType() {
		return "HelloMessage";
	}

	@Override
	public Message processMessage(Message message) {
		NodeInfo node = message.getSender();
		
		HelloReplyMessage reply = new HelloReplyMessage();
		
		HelloType type = (HelloType) message.getContents();
		if (type == HelloType.HI) {
			if (!containsNode(node)) {
				nodes.add(node);
			}
			
			reply.setContents(HelloType.HI);
		} else {
			if (!containsNode(node)) {
				nodes.remove(node);
			}
			
			reply.setContents(HelloType.BYE);
		}
		
		reply.setHelloer(message.getSender());
	
		return reply;
	}

	@Override
	public boolean hasReply() {
		return true;
	}
	
	private boolean containsNode(NodeInfo node) {
		Iterator<NodeInfo> _nodes = nodes.iterator();
		while (_nodes.hasNext()) {
			if (_nodes.next().equals(node)) {
				return true;
			}
		}
		return false;
	}
}

@@ -27,16 +27,84 @@
 ocols;%0A%0A
+import java.net.Inet4Address;%0Aimport java.net.UnknownHostException;%0A
 import j
@@ -636,24 +636,413 @@
 etSender();%0A
+%09%09if (node.getLocation().equals(%22127.0.0.1%22)) %7B%0A%09%09%09try %7B%0A%09%09%09%09String addr = Inet4Address.getLocalHost().getHostAddress();%0A%09%09%09%09node.addLocation(addr);%0A%09%09%09%7D catch (UnknownHostException e) %7B%0A%09%09%09%09/*%0A%09%09%09%09 * If this fails, the node might become unreachable %0A%09%09%09%09 * to other machines on the network%0A%09%09%09%09 * It's not a fatal error anyways...%0A%09%09%09%09 */%0A%09%09%09%09System.err.println(e.getMessage());%0A%09%09%09%7D%0A%09%09%7D%0A
 %09%09%0A%09%09HelloRe

Fix bug in HelloProtocol where the registering node