package hsr.dsa.network;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Random;

import net.tomp2p.connection.Bindings;
import net.tomp2p.dht.PeerBuilderDHT;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.replication.IndirectReplication;

public class Node implements Closeable {
private static final Random RANDOM = new Random();
	private PeerDHT peer;
	private final short port;

	public Node(short port, InetAddress bingAddress) throws IOException {
		this.port = port;
		
		Bindings bindings = new Bindings();
		bindings.addAddress(bingAddress);

		this.peer = new PeerBuilderDHT(new PeerBuilder(new Number160(RANDOM)).bindings(bindings).ports(port).start()).start();
		new IndirectReplication(this.peer).start();
	}
	
	public Node(short port) {
		this.port = port;
	}

	public short getPort() {
		return this.port;
	}
	
	protected PeerDHT getPeer() {
		return this.peer;
	}
	
	protected void setPeer(PeerDHT peer) {
		this.peer = peer;
	}

	@Override
	public void close() throws IOException {
		this.peer.peer().announceShutdown().start().awaitListenersUninterruptibly();
		this.peer.peer().shutdown();
	}
}

