/**
 * Some sample OpenChord code.  See OpenChord manual and javadocs for more detail.
 * @author Jonathan Engelsma
 */

import java.net.InetAddress;
import java.net.MalformedURLException;
import de.uniba.wiai.lspi.chord.data.URL;
import de.uniba.wiai.lspi.chord.service.*;
import de.uniba.wiai.lspi.chord.service.impl.*;

import java.util.*;
import java.io.Serializable;

public class ChordClient
{
	private Chord myChord;
	
	public Chord chord()
	{
	    return myChord;
    }

    public ChordClient(String masterHost, boolean master)
    {
		try
		{
			if (master)
				createNetwork(masterHost);
			else
				joinNetwork(masterHost);				
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
    
	public void createNetwork(String host)
	{
		System.out.println("Creating Chord network on \"" + host + "\"");
		String protocol = URL.KNOWN_PROTOCOLS.get(URL.SOCKET_PROTOCOL);
		URL localURL = null;
		try
		{
			localURL = new URL(protocol + "://" + host + ":5353/");
		}
		catch (MalformedURLException e)
		{
			throw new RuntimeException(e);
		}
		
		myChord = new ChordImpl();
	
		try
		{
			myChord.create(localURL);
		}
		catch (ServiceException e)
		{
			throw new RuntimeException("Error: Could not create DHT!", e);
		}
		
	}
	
	public void joinNetwork(String host)
	
	{
		System.out.println("Joining Chord network on \"" + host + "\"");		
		String protocol = URL.KNOWN_PROTOCOLS.get(URL.SOCKET_PROTOCOL);		
		URL localURL = null;
		try
		{
			localURL = new URL(protocol + "://" + InetAddress.getLocalHost().getHostAddress() + ":5354/");			
		}
		catch (MalformedURLException e)
		{
			throw new RuntimeException(e);
		}
		catch (Exception ex)
		{
			throw new RuntimeException(ex);
		}
		
		URL bootstrapURL = null;
		try
		{
			bootstrapURL = new URL( protocol + "://" + host + ":5353/");	
		}
		catch (MalformedURLException e)
		{
			throw new RuntimeException (e);
		}
		myChord = new ChordImpl();
		try
		{
			myChord.join(localURL , bootstrapURL);
		}
		catch (ServiceException e)
		{
			throw new RuntimeException("Error: Could not join DHT!", e);
		}		
					
	}    
}
