/*
 * SenderBehaviour.java
 *
 * Created on April 27, 2005, 3:47 PM
 */

package DDMT.core.behaviour;

import java.util.*;

import jade.core.behaviours.*;
import jade.lang.acl.*;

/**
 *
 * @author  jk3
 */
    public class SenderBehaviour extends jade.core.behaviours.CyclicBehaviour
    {
        //template for incoming messages
        MessageTemplate mt;
        
        //The current state of the agent
        int state = 0;
        
        //Queue of messages to send
        LinkedList messages;
        
        public SenderBehaviour(String filter)
        {
            messages = new LinkedList();
            mt = MessageTemplate.MatchConversationId("postofficefilter");
        }
        
        public void action() {
            //if it's ready to send a message, send it
            if( state == 0 )
            {
                //Check for messages to send
                Iterator iter = messages.iterator();
                while( iter.hasNext() )
                {
                    myAgent.send((ACLMessage)iter.next());
                    iter.remove();
                    
                    //put into 'expect reply' state
                    state = 1;
                }
            }
            
            //Otherwise if it's waiting for a reply...
            else if( state == 1 )
            {
                //check for messages
                ACLMessage incoming = myAgent.receive(mt);
                if( incoming != null )
                {
                    state = 0;
                }
            }
            
            //Otherwise nothing is happening, so wait
            block(100);
        }  
        
        public void addMessage(ACLMessage m)
        {
            messages.add(m);
        }
        
    }