
package qms.group;
import java.net.*;
import java.io.*;
import qms.io.*;
/**
 * Un nodo del gruppo
 * @author  Enrico
 */
public class Node implements Comparable {
    protected static Node local_node;
    static {
        try {
            local_node = new  Node();
            local_node.setName("qms");
            local_node.setAccessPoint( new URL("http://localhost/qms"));            
        } catch (Exception e) {
            throw new IllegalStateException("Can't initialize current node ids");
        }
    }
    public  static Node getLocalNode() {
        return local_node;
    }
    
    protected static NodeAccessPoint local_access_point = null;
    
    public static void setLocalAccessPoint(NodeAccessPoint nap) {
        local_access_point = nap;
    }
    
    public static NodeAccessPoint getLocalAccessPoint() {
        return local_access_point;
    }
    
    protected URL access_point;
    protected int priority;
    protected String name;
    protected int fault_count;
    
    public Node() {
        access_point = null;
        priority = -1;
        fault_count =  0;
        name = "unnamed"+System.currentTimeMillis();
    }
    public int getFaultCount() {
        return fault_count;
    }
    public void incFaultCount() {
        fault_count++;
    }
    
    public void setPriority(int p) { this.priority = p; }
    public int getPriority() { return priority; }
    public URL getAccessPoint() {
        return access_point;
    }
    public void setAccessPoint(URL ap) {
        this.access_point = ap;
    }
    public String toString() {return name; }
    /**
     * Getter for property name.
     * @return Value of property name.
     */
    public java.lang.String getName() {
        return name;
    }
    /**
     * Ricalcola la priorità del nodo in base al nome
     */
    public void calculatePriority() {
        int p = 0;
        for (int i = 0; i < name.length(); i++) {
            p +=  name.charAt(i);
        }
        setPriority(p);
    }
    /**
     * Setter for property name.
     * @param name New value of property name.
     */
    public void setName(java.lang.String name) {
        this.name = name;
        calculatePriority();
    }
    /**
     * Due nodi sono lo stesso se hanno lo stesso nome
     */
    public boolean equals(Object o) {
        Node on = (Node) o;
        return on.name.equals(name);
    }
    public int compareTo(Object obj) {
        Node o = (Node) obj;
        if (name.equals(o.name)) return 0;
        
        return o.priority-priority;
    }
    
}
