/*
 * 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.*;
/**
 * Elimina un messaggio da tutti i nodi
 * @author  Enrico
 */
public class DeleteMessageAction implements Action, WaitingAction, MessageListener, QueueLifeListener {    
    
    protected String queueid;
    protected String msgid;
    protected Controller controller;
    protected boolean finished;    
    protected boolean waiting;
    protected boolean started;
    protected int sent_count;
    protected int required_count;
    protected WaitingAction waiter;
    
    public DeleteMessageAction(String queueid, String msgid, Controller controller, WaitingAction waiter) {
        this.queueid = queueid;
        this.controller = controller;
        this.finished = false;    
        this.msgid = msgid;
        this.waiting = true;
        this.waiter = waiter;
        this.sent_count = 0;
        this.required_count = controller.getGroup().size();
        this.started = false;
        controller.getQueues().getQueue(queueid).addQueueLifeListener(this);
    }
        
    public boolean isFinished() {
        if (finished) return true;
        
        if (sent_count >= required_count) {
            finished = true;
            waiter.canStart();            
        }
        return finished;
    }
    
    public void runStep() {       
        if (waiting) return;
        if (!started) {
            started = true;
            Message cont = new Message( 
                    Node.getLocalNode().getName(),
                    Multicaster.ALL, 
                    queueid, 
                    "queue_delete_message", 
                    msgid);
            cont.setListener(this);
            controller.getMulticaster().castMessage(cont);                     
        }
    }
    public String toString() { return "delete ("+sent_count+"/"+required_count+") msg "+msgid+" from queue "+queueid; }
    
    public void canStart() {
        waiting = false;
    }
    
    public void notifyMessageDelivered(Message who, boolean status) {
        if (status) {
            sent_count++;                        
        }   
    }
    
    public void queueDestroyed(MessageQueue queue) {
        finished = true;
    }    
    public void cancel() {
        finished = true;
        waiter.cancel();
    }
    
    public void notifyNodeRemoved(Node n) {
        required_count--;
    }
    
}
