package system;

import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import java.io.IOException;

import javax.swing.JOptionPane;

import communication.Order;

/**
 * Zachowanie wysyłające zamówienie do agenta translatora.
 * 
 * @author Mateusz Kaflowski <mkaflowski@gmail.com>
 */
public class SendOrderBehaviour extends OneShotBehaviour {

	/**Zamówienie*/
	Order order;

	public SendOrderBehaviour(Order order) {
		this.order = order;
	}

	@Override
	public void action() {
		
		//wyszukanie translatora w YP:
		DFAgentDescription dfd = new DFAgentDescription();
		
		ServiceDescription sd = new ServiceDescription();
		sd.setType("Manager");
		
		dfd.addServices(sd);
		DFAgentDescription result = null;
		
		try {
			if(DFService.search(myAgent, dfd).length==0)
			{
				System.out.println("there is no translator agent");
				JOptionPane.showMessageDialog(null, "There is no manager agent in the system!","Error",
					    JOptionPane.ERROR_MESSAGE);
				return;
			}
			result = DFService.search(myAgent, dfd)[0];
		} catch (FIPAException e1) {
			System.out.println("searching translator error!");
			JOptionPane.showMessageDialog(null, "Searching manager agent problem","Error",
				    JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		//wysyłanie zamówienia:	
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);

		msg.addReceiver(result.getName());
		

		try {
			msg.setContentObject(order);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Sending message " + order + " problem.","Error",
				    JOptionPane.ERROR_MESSAGE);
		}

		myAgent.send(msg);
		JOptionPane.showMessageDialog(null, "Order " + order + " sent succesfully.");
		
	}

}
