package agents;

import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.ServiceDescription;

public class Searcher extends Agent {

    private String targetService;

    private void print(String data, String behaviourId) {
        if (behaviourId != null)
            System.out.println("A[" + getLocalName() + "|" + behaviourId + "] " + data);
        else
            System.out.println("A[" + getLocalName() + "] " + data);
    }

    private class SearchBehaviour extends OneShotBehaviour {
        @Override
        public void action() {
            DFAgentDescription template = new DFAgentDescription();
            ServiceDescription tsd = new ServiceDescription();
            tsd.setType(targetService);
            template.addServices(tsd);

            try {
                DFAgentDescription[] results = DFService.search(myAgent, template);
                print("found " + results.length + " agent(s) providing " + targetService + ":", "SearchBehaviour");
                for (DFAgentDescription d : results) {
                    print("  -> " + d.getName().getLocalName(), "SearchBehaviour");
                }
            } catch (FIPAException e) {
                print("DF search error: " + e.getMessage(), "SearchBehaviour");
            }

            myAgent.doDelete();
        }
    }

    @Override
    protected void setup() {
        Object[] args = getArguments();
        targetService = (args != null && args.length > 0) ? (String) args[0] : "Service1";
        print("searching for: " + targetService, null);
        addBehaviour(new SearchBehaviour());
    }

    @Override
    protected void takeDown() {
        print("terminated", null);
    }
}
