package org.greenstone.p2p;

import java.io.*;
import java.net.*;
import java.util.*;

public class NameServer
{ ServerList list;
  URL        parent;
  Vector     childServers; // name servers
  Vector     children;     // greenstone servers
  String     identity;
  Map        actionMap;
 
  public NameServer(String identity)
  { this.list     = new ServerList();
    this.identity = identity;
    this.parent   = null;
    this.children = new Vector();
    this.childServers = new Vector();

    this.actionMap = new HashMap();

    NameServerAction listServersAction = new ListServersAction(this);
    this.addAction(listServersAction);
    NameServerAction defaultAction = new DefaultServerAction(this);
    this.addAction(defaultAction);
    
    // set up registration listener
    // set up messaging broadcaster
    // set up messaging listener
  }

  private void addAction(NameServerAction action)
  { this.actionMap.put(action.getActionName(), action);
  }

  private void loadChildren(BufferedReader in)
  { try 
      { String child = in.readLine();
      }
    catch (IOException ex)
      {
      }
  }

  private void loadServers(BufferedReader in)
  { try
      { String child = in.readLine();
      }
    catch (IOException io)
      {
      }
  }

  public void sendMessage(URL origin, String actionName, Map parameters)
  { NameServerAction action = (NameServerAction) this.actionMap.get(actionName);
    if (action != null)
      { action.doAction(origin, parameters);
      }
    else
      { System.out.println("Sending action " + actionName + " through <default>");

	// TODO: add action name to the parameter map so that it is not lost...
	action = (NameServerAction) this.actionMap.get("Default");
	if (action != null)
	{ action.doAction(origin, parameters);
	}
      }
    //NameServerAction action = NameServerActionFactory.createAction(action, parameters);
    //action.doAction();
  }

  public void receiveResponse(URL responseTo, ClientResponse response)
  { GreenstoneInterface.receiveResponse(responseTo, response);
  }
    
  private void loadParent()
  {
  }

  public String getIdentity()
  { return this.identity;
  }
  
  public void setParent(URL parent)
  { this.parent = parent;
  }
  
  public URL getParent()
  { return this.parent;
  }
  
  public void addSubServer(URL subserver)
  { this.childServers.add(subserver);
  }
  
  public void registerServer(URL child)
  { System.out.println("Receiving registration from " + child.toString());
    this.children.add(child);
  }
  
  public Enumeration subServers()
  { return this.childServers.elements();
  }
  
  public Enumeration servers()
  { return this.children.elements();
  }

  public static boolean pollServer(URL server)
  { return false;
  }

  /**
   *  
   */
  public static void main(String args[])
  { NameServer server = new NameServer(args[0]);

    // Load the action items
    // Wait for signals
  }
}