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

package qms.queue.actions;
import qms.queue.*;
import qms.group.*;
import qms.util.*;
import qms.messages.*;
/**
 * Scongela tutti i nodi del gruppo e aspetta che siano tutti congelati
 * @author  Enrico
 */
public class UnFreezeGroupAction implements Action, MessageListener, WaitingAction {    
        
    protected Controller controller;
    protected boolean finished;     
    protected boolean started;
    protected boolean waiting;
    protected int sent_count;
    protected int required_count;
    protected WaitingAction waiter;
    
    public UnFreezeGroupAction(Controller controller, WaitingAction waiter) {        
        this.controller = controller;
        this.finished = false;        
        this.waiter = waiter;
        this.sent_count = 0;
        this.required_count = controller.getGroup().size();
        this.started = false;        
        this.waiting = true;        
    }
        
    public boolean isFinished() {
        return finished;
    }
    
    public void runStep() {       
        if (waiting) return;
        if (finished) return;
        if (!started) {
            started = true;
            Logger.log("Sending group_ready to every node. I have got "+controller.getGroup().size()+" peers");
            Message cont = new Message( 
                    Node.getLocalNode().getName(),
                    Multicaster.ALL, 
                    QueuesManager.GROUP_QUEUE_ID, 
                    "group_ready", 
                    "");
            cont.setListener(this);
            controller.getMulticaster().castMessage(cont);                     
        }
    }
    public String toString() { return "unfreeze group"; }        
    
    public void notifyMessageDelivered(Message who, boolean status) {
        if (status) {
            sent_count++;                        
        } else {
            required_count--;
        }
        if (sent_count == required_count) {
            finished = true;            
            waiter.canStart();
        }
    }        
    
    public void canStart() {
        waiting = false;
    }
    
    public void cancel() {
        finished = true;
        waiter.cancel();
    }
    
    public void notifyNodeRemoved(Node n) {
    }
    
}
