/*
 * 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.*;
/**
 * Acquisizione della ownership su di una coda
 * @author  Enrico
 */
public class LockQueueAction implements Action, QueueLifeListener {    
    
    protected String queueid;
    protected Controller controller;
    protected boolean finished;
    protected int status;
    protected WaitingAction waiter;
    protected String lockid;
    
    public LockQueueAction(String queueid, String lockid, Controller controller, WaitingAction waiter) {
        this.lockid = lockid;
        this.queueid = queueid;
        this.controller = controller;
        this.finished = false;
        this.status = 0;        
        this.waiter = waiter;                
        controller.getQueues().getQueue(queueid).addQueueLifeListener(this);
    }
        
    public boolean isFinished() {
        return finished;
    }
    protected void checkFinished() {
        MessageQueue queue = controller.getQueues().getQueue(queueid);
        if (queue.checkAndAcquireLock(lockid)) {            
            finished = true;
            Logger.log("Lock acquired on queue "+queueid);
            waiter.canStart();
        }
    }
    public void runStep() {
        if (status == 0) {                        
            Message request_lock = new Message( 
                    Node.getLocalNode().getName(),
                    Multicaster.ALL, 
                    queueid, 
                    "queue_request_lock", 
                    lockid);
            controller.getMulticaster().castMessage(request_lock);
            status = 1;            
            return;
        }
        checkFinished();
    }
    public String toString() { return "lock "+queueid+" lockid="+lockid; }
    
    public void queueDestroyed(MessageQueue queue) {
        finished = true;
    }
    public void notifyNodeRemoved(Node n) {        
    }    
    
}
