
/**
 * SGRBA.java
 *
 * @author Wanderson C. Bragança <wanderson.wbc@gmail.com>
 * @link http://www.wanderson.wordpress.com
 * @copyright Copyright © 2009
 * @version  14/04/2009
 */

import jade.core.*;
import jade.core.behaviours.*;
import jade.content.onto.basic.*;
import jade.domain.*;
import jade.domain.mobility.*;
import jade.domain.JADEAgentManagement.*;
import jade.gui.*;
import java.util.Vector;
import java.util.Iterator;
import jade.domain.FIPANames;
import jade.content.lang.sl.SLCodec;
import jade.domain.FIPAAgentManagement.AMSAgentDescription;
import jade.domain.FIPAAgentManagement.SearchConstraints;
import jade.gui.GuiEvent;
import jade.lang.acl.ACLMessage;
import javax.swing.JOptionPane;


public class SGRBA extends GuiAgent{
    
    Location nextSite;
    
    transient protected SGRBAGui myGui;
    public static final int SAIR        = 1;
    public static final int MOVE_AGENTE = 2;
    public static final int KILL_AGENTE = 3;
    public static final int NOVO_AGENTE = 4;
    public static final int CLONE_AGENTE= 5;
    public static final int ATUALIZAR   = 6;
    public static final int PARAR_MONITORAMENTO_WEB   = 7;
    public static final int INICIAR_MONITORAMENTO_WEB   = 8;
    public int cont=0;
    private Vector agents = new Vector();
    private jade.wrapper.AgentContainer home;
    jade.core.Runtime runtime = jade.core.Runtime.instance();
    public SGRBA() {
        
    }
    @Override
    public void setup(){
        
        // registra  SL0 language
        getContentManager().registerLanguage(new SLCodec(), FIPANames.ContentLanguage.FIPA_SL0);

        // registra  mobility ontology
        getContentManager().registerOntology(MobilityOntology.getInstance());
        home = runtime.createAgentContainer(new ProfileImpl());

        // cria form
        myGui = new SGRBAGui(this);
        myGui.changeLookAndFeel(2);
        myGui.setVisible(true);       
               
        // pega a lista de plataformas disponíveis e exibe na GUI
        addBehaviour(new PegaLocaisDiponiveis(this));

        Behaviour b1 = new MensagensRecebidas(this);
        addBehaviour(b1);
       
        
    }
    @Override
    public void takeDown() {
        if(myGui!=null) {
            myGui.dispose();
            myGui.setVisible(false);
        }
        JOptionPane.showMessageDialog(null, getLocalName()+ " Saindo !! ");
    }
    
    //implementa metodo onGuiEvent da interface jade.gui.*
    public void onGuiEvent(GuiEvent ev) {
        
        switch(ev.getType()) {
            case SAIR:
                myGui.dispose();
                myGui = null;
                doDelete();
                System.exit(0);
                break;
            case KILL_AGENTE:
                // PEGA O NOME DO AGENTE A SER REMOVIDO
                String agentName = (String)ev.getParameter(0);
                // LOCALIZA O AGENTE
                AID aid = new AID(agentName, AID.ISLOCALNAME);
                KillAgent ka = new KillAgent();
                ka.setAgent(aid);
                // CRIA UM COMPORTAMENTO: ENVIA A ORDEM DE DESTRUI��O PARA O AGENTE
                addBehaviour(new  EnviaMsg(this,new Action(aid, ka)));
                // REMOVE O AGENTE DA LISTA
                agents.remove(agentName);
                // ATUALIZA A LISTA NA GUI
                myGui.updateList(agents);
                break;
            case MOVE_AGENTE:
                // PEGA O NOME DO AGENTE A SER MOVIDO
                String agentName1 = (String)ev.getParameter(1);
                AID aid1 = new AID(agentName1, AID.ISLOCALNAME);
                // PEGA O LOCAL DE DESTINO
                Iterator MoveParameters = ev.getAllParameter();
                nextSite =(Location)MoveParameters.next();
                String p = (String)ev.getParameter(2);
                MobileAgentDescription mad1 = new MobileAgentDescription();
                mad1.setName(aid1);
                mad1.setDestination(nextSite);
                mad1.setSignature(p);
                MoveAction ma = new MoveAction();
                ma.setMobileAgentDescription(mad1);
                addBehaviour(new  EnviaMsg(this,new Action(aid1, ma)));
                
                doWait(2000);
                myGui.updateLocaisVisitados(nextSite,p);
                KillAgent ka2 = new KillAgent();
                ka2.setAgent(aid1);
                addBehaviour(new  EnviaMsg(this,new Action(aid1, ka2)));
                agents.remove(agentName1);
                myGui.updateList(agents);
                break;                
               
            case ATUALIZAR:
                addBehaviour(new PegaLocaisDiponiveis(this));
                break;
            case INICIAR_MONITORAMENTO_WEB:
                AMSAgentDescription [] ag1 = null;
                try {
                    SearchConstraints c1 = new SearchConstraints();
                    c1.setMaxResults(new Long(-1));
                    ag1 = AMSService.search( this, new AMSAgentDescription(), c1 );
                } catch (Exception e) {
                    System.out.println( "Problema na pesquisa do AMS: " + e );
                    e.printStackTrace();
                }
                ACLMessage m1 = new ACLMessage(ACLMessage.INFORM);
                m1.setContent( "iniciar-monitoramento-web" );
                for (int i=0; i<ag1.length;i++){
                    m1.addReceiver(ag1[i].getName());
                }
                send(m1);
                JOptionPane.showMessageDialog(null,"Iniciando Monitoramento Web");
                break;

            case PARAR_MONITORAMENTO_WEB:
                AMSAgentDescription [] ag = null;
                try {
                    SearchConstraints c = new SearchConstraints();
                    c.setMaxResults(new Long(-1));                    
                    ag = AMSService.search( this, new AMSAgentDescription(), c );
                } catch (Exception e) {
                    System.out.println( "Problema na pesquisa do AMS: " + e );
                    e.printStackTrace();
                }
                ACLMessage m = new ACLMessage(ACLMessage.INFORM);
                m.setContent( "parar-monitoramento-web" );
                for (int i=0; i<ag.length;i++){
                    m.addReceiver(ag[i].getName());
                }
                send(m);
                JOptionPane.showMessageDialog(null,"Parando Captura de pacotes");
                break;
            case NOVO_AGENTE:
                jade.wrapper.AgentController a = null;
                try {
                    Object[] args = new Object[2];
                    args[0] = getAID();
                    String name;
                    // Cria um nome para o agente
                    name = "AgenteEscravo"+cont++;
                    a = home.createNewAgent(name, AgenteEscravo.class.getName(), args);
                    a.start();
                    // Adiciona o agente na lista
                    agents.add(name);
                    // Exibe na GUI
                    myGui.updateList(agents);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null,"Problema na criação do Agente ");
                }
                break;
        }
        
    }
}
