/*
 * LockQueueAction.java
 *
 * Created on 26 marzo 2004, 13.37
 */

package qms.queue.actions;
import qms.queue.*;
import qms.group.*;
import qms.util.*;
import qms.messages.*;
/**
 * Congela tutti i nodi del gruppo e aspetta che siano tutti congelati
 * @author  Enrico
 */
public class FreezeGroupAction implements Action, MessageListener{    
        
    protected Controller controller;
    protected boolean finished;     
    protected boolean started;
    protected int sent_count;
    protected int required_count;
    protected WaitingAction waiter;
    
    public FreezeGroupAction(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;        
    }
        
    public boolean isFinished() {
        if (finished) return true;
        
        if (sent_count == required_count) {
            finished = true;            
            waiter.canStart();
        }
        return finished;
    }
    
    public void runStep() {       
        if (!started) {
            started = true;
            Message cont = new Message( 
                    Node.getLocalNode().getName(),
                    Multicaster.ALL, 
                    QueuesManager.GROUP_QUEUE_ID, 
                    "group_freeze", 
                    "");
            cont.setListener(this);
            controller.getMulticaster().castMessage(cont);                     
        }
    }
    public String toString() { return "freeze group"; }        
    
    public void notifyMessageDelivered(Message who, boolean status) {
        if (status) {
            sent_count++;                        
        } else {
            required_count--;
        }        
    }    
    public void notifyNodeRemoved(Node n) {
        required_count--;
    }
}
