/*
 * Created on 26 marzo 2004, 13.37
 */

package qms.queue.actions;
import qms.queue.*;
import qms.group.*;
import qms.util.*;
import java.util.*;
import qms.messages.*;
/**
 * Dice a tutti i nodi del gruppo che un nuovo nodo è pronto
 * @author  Enrico
 */
public class InformNewNodeExistanceAction implements Action, WaitingAction, MessageListener{
    
    protected Node node;
    protected Controller controller;
    protected boolean finished;
    protected boolean sending_finished;
    protected boolean waiting;
    protected boolean started;
    protected int sent_count;
    protected int required_count;
    protected WaitingAction waiter;
    
    public InformNewNodeExistanceAction(Controller controller, Node node, WaitingAction waiter) {
        this.controller = controller;
        this.finished = false;
        this.node = node;
        this.waiting = true;
        this.waiter = waiter;
        this.sent_count = 0;
        this.sending_finished = false;
        this.required_count = controller.getGroup().size();
        this.started = false;
    }
    
    public boolean isFinished() {
        if (!finished) {
            if ((sending_finished) && (sent_count == required_count)) {
                finished = true;
                waiter.canStart();
            }
        }
        return finished;
    }
    
    public void runStep() {
        if (waiting) return;
        if (finished) return;
        if (!started) {
            sending_finished = false;
            started = true;
            required_count = 0;           
                        
                Message cont = new Message(
                            node.getName(),
                            Multicaster.ALL,                            
                            QueuesManager.GROUP_QUEUE_ID,
                            "group_node_exists",
                            node.getAccessPoint().toString());                    
                                
                cont.setListener(this);
                required_count = controller.getGroup().size();
                controller.getMulticaster().castMessage(cont);
            
            
            
            sending_finished = true;                        
        }
    }
    public String toString() { return "inform new node existance of "+node; }
    
    public void canStart() {
        waiting = false;
    }
    
    public void notifyMessageDelivered(Message who, boolean status) {                
        if (status) {
            sent_count++;                        
        }  else {
            required_count--;
        }
    }
    public void cancel() {
        finished = true;
        waiter.cancel();
    }
    public void notifyNodeRemoved(Node n) {
        required_count--;
    }
}
