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

package qms.queue.actions;
import qms.queue.*;
import qms.group.*;
import qms.messages.*;
import java.util.*;
/**
 * Guarda se ci sono dei "request_lock" nello stack delle code.
 * Se ne trova uno vede se è possobile concedere il permesso e poi invia il permesso al nodo mittente
 * @author  Enrico
 */
public class AnswerLockRequestsAction implements Action {
    
    protected Controller controller;
    
    public AnswerLockRequestsAction(Controller controller) {
        this.controller = controller;
    }
    
    public boolean isFinished() {
        return false;
    }
    public void runStep() {
        Group nodes = controller.getGroup();
        QueuesManager queues = controller.getQueues();
        for (Iterator i = queues.queueNames(); i.hasNext();) {
            String qid = (String) i.next();
            MessageQueue q = queues.getQueue(qid);
            if (!q.isLocked()) {                                
                List can_answer_agree_messages = q.findAgreeableLockMessages();                                
                for (Iterator a = can_answer_agree_messages.iterator(); a.hasNext();) {
                    Message m = (Message) a.next();
                    String lockid = m.getBody();
                    Node new_owner = nodes.lookupNode(m.getSender());
                    q.addOwner(new_owner);
                    Message agree = new Message( Node.getLocalNode().getName(),
                                                 new_owner.getName(),
                                                 q.getId(),
                                                 "queue_agree_lock",lockid);
                    controller.getMulticaster().castMessage(agree);
                }
            }
        }
    }
    public String toString() { return "answer lock requests"; }
    
    public void notifyNodeRemoved(Node n) {
    }    
    
}
