
/**
 * AgenteEscravo.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.domain.JADEAgentManagement.KillAgent;
import jade.core.*;
import jade.core.behaviours.*;
import jade.content.*;
import jade.content.lang.sl.*;
import jade.content.onto.basic.*;
import jade.domain.*;
import jade.domain.mobility.*;
import javax.swing.JOptionPane;
import jade.core.Agent;
import jade.domain.AMSService;
import jade.domain.FIPAAgentManagement.*;
import jade.lang.acl.*;
import java.io.IOException;

public class AgenteEscravo extends Agent {

    private AID controller;
    private Location destination;
    transient protected HttpSniff cap;
    private Thread th;

    @Override
    protected void setup() {
        // Pega lista de argumentos enviados na criação do agente
        Object[] args = getArguments();
        controller = (AID) args[0];
        destination = here();
        getContentManager().registerLanguage(new SLCodec(), FIPANames.ContentLanguage.FIPA_SL0);
        getContentManager().registerOntology(MobilityOntology.getInstance());
        addBehaviour(new receiveCommands(this));
        addBehaviour(new ReceiveMsg(this));
    }

    @Override
    protected void beforeMove() {
        JOptionPane.showMessageDialog(null, "Movendo-se agora para o container " + destination.getName());

    }

    protected void afterMove() {
        JOptionPane.showMessageDialog(null, "Agente escravo chegou no : " + destination.getName());
       
    }

    public void tentaMover(AID id, Location l, String pl) {
        AMSAgentDescription[] agents = null;
        SearchConstraints c = new SearchConstraints();
        try {
            c.setSearchId(id.getName());
            agents = AMSService.search(this, new AMSAgentDescription(), c);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Problema na procura pelo AMS ");
            e.printStackTrace();
        }
        ACLMessage m = new ACLMessage(ACLMessage.INFORM);
        if (l != null) {
            doMove(destination = l);
        } else {
            JOptionPane.showMessageDialog(null, "Erro ao tentar mover o agente");
        }
    }

    public void startSniffer() {
        th = new Thread(new Runnable() {

            public void run() {
                try {
                    cap = new HttpSniff();
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null, "Não conseguiu criar o objeto para executar o Sniffer");
                    ex.printStackTrace();
                }
                try {
                    // Inicia o processo de captura
                    cap.run();

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Não conseguiu executar o Sniffer");
                    ex.printStackTrace();
                }
            }
        });
        th.start();
    }

    class ReceiveMsg extends CyclicBehaviour {

        private ReceiveMsg(Agent a) {
            super(a);
        }

        @Override
        public void action() {
            ACLMessage msg = receive();
            if (msg != null) {
                if (msg.getContent().equals("parar-monitoramento-web")) {
                    cap.stopCapture();
                    th.interrupt();
                    ACLMessage m = new ACLMessage(ACLMessage.INFORM);
                    m.setContent("Processo de captura finalizado");
                    m.addReceiver(msg.getSender());
                    send(m);
                } else if (msg.getContent().equals("iniciar-monitoramento-web")) {
                    startSniffer();
                }
            }
            block();
        }
    }

    class receiveCommands extends CyclicBehaviour {

        receiveCommands(Agent a) {
            super(a);
        }

        public void action() {
            ACLMessage msg = receive(MessageTemplate.MatchSender(controller));
            if (msg == null) {
                block();
                return;
            }
            if (msg.getPerformative() == ACLMessage.REQUEST) {
                try {
                    ContentElement content = getContentManager().extractContent(msg);
                    Concept concept = ((Action) content).getAction();
                    if (concept instanceof MoveAction) {
                        MoveAction ma = (MoveAction) concept;
                        AID ID = ma.getMobileAgentDescription().getName();
                        Location l = ma.getMobileAgentDescription().getDestination();
                        String p = ma.getMobileAgentDescription().getSignature();
                        tentaMover(ID, l, p);
                    } else if (concept instanceof KillAgent) {
                        doDelete();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
