package partyscenario;

import java.util.Random;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.AMSService;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.AMSAgentDescription;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;
import jade.domain.FIPAAgentManagement.SearchConstraints;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.proto.ProposeResponder;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;


public class HostAgent extends Agent{
	
	private int capacidad_comida;
	private int capacidad_bebida;
	private Random r = new Random();
	
	 protected void setup() {
		 	capacidad_comida = r.nextInt(30)+1;
			capacidad_bebida = r.nextInt(30)+1;
		    DFAgentDescription dfd = new DFAgentDescription();
		    dfd.setName(getAID());
		    ServiceDescription sd = new ServiceDescription();
		    sd.setType("attendant");
		    sd.setName("Host");
		    dfd.addServices(sd);
		    try {
		      DFService.register(this, dfd);
		    }
		    catch (FIPAException fe) {
		      fe.printStackTrace();
		    }
		    System.out.println("el agente "+ getLocalName() +" ha iniciado la fiesta");
            SearchConstraints ALL = new SearchConstraints();
            ALL.setMaxResults(new Long(-1));
            try {
				AMSAgentDescription[] result = AMSService.search(this, new AMSAgentDescription (), ALL);
				ACLMessage comienzo = new ACLMessage(ACLMessage.INFORM);
				comienzo.setContent("a trabajar");
				for (int i=0; i<result.length;i++){
					if (result[i].getName().getLocalName().startsWith("WAITER"))
						comienzo.addReceiver(result[i].getName());
				}
			send(comienzo);
			} catch (FIPAException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            addBehaviour(new TickerBehaviour(this, 10000){

				@Override
				protected void onTick() {
					DFAgentDescription template = new DFAgentDescription();
		            ServiceDescription sd1 = new ServiceDescription();
		            sd1.setType("attendant");
		            template.addServices(sd1);
		            SearchConstraints ALL = new SearchConstraints();
		            ALL.setMaxResults(new Long(-1));
		            try {
		            	DFAgentDescription[] result = DFService.search(myAgent, template, ALL);
		            	if(result.length<=1)
		            	{
		            		System.out.println(getLocalName()+ ": hora de cerrar el chiringuito");
		            		doDelete();
		            	}
		            }
		            catch(FIPAException e){
		            	e.printStackTrace();
		            }
				}
            	
            });
		    addBehaviour(new CyclicBehaviour(){

				@Override
				 public void action() {
					MessageTemplate mt = MessageTemplate.or(MessageTemplate.MatchContent("gran fiesta, adios"),MessageTemplate.MatchContent("hola, he llegado"));
					ACLMessage msg = myAgent.receive(mt);
				    if (msg != null) {
				    	if(msg.getContent().compareTo("hola, he llegado")==0)
				    	{
						    System.out.println(getLocalName()+": agente " +msg.getSender().getLocalName()+ " bienvenido a mi fiesta");
						    ACLMessage reply = msg.createReply();
						    reply.setContent("Bienvenido");
						    myAgent.send(reply);
				    	}
				    	else
				    	{
				    		System.out.println(getLocalName()+": el agente " +msg.getSender().getLocalName()+ " se marcha");
						    ACLMessage reply = msg.createReply();
						    reply.setContent("hasta la próxima");
						    myAgent.send(reply);
				    	}
				    }
					else {
						block();
					}
				  }   	
		    });
		    MessageTemplate plantilla = ProposeResponder.createMessageTemplate(FIPANames.InteractionProtocol.FIPA_PROPOSE);
	        this.addBehaviour(new Responderofrecimiento(this, plantilla));
	 }
	    private class Responderofrecimiento extends ProposeResponder {
		   	 
	        public Responderofrecimiento(Agent agente, MessageTemplate plantilla) {
	            super(agente, plantilla);
	        }
	 
	        protected ACLMessage prepareResponse(ACLMessage propuesta)
	                throws NotUnderstoodException {
	 
	            if (HostAgent.this.Decision(propuesta.getContent())) {
	                System.out.println(this.myAgent.getLocalName()+ ": Si, tomare algo");
	                if(propuesta.getContent().compareTo("comida")==0)
	                	capacidad_comida--;
	                else
	                	capacidad_bebida--;
	                ACLMessage agree = propuesta.createReply();
	                agree.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
	                return agree;
	            }
	            else {
	                System.out.println(this.myAgent.getLocalName()+ ": No gracias");
	                ACLMessage refuse = propuesta.createReply();
	                refuse.setPerformative(ACLMessage.REJECT_PROPOSAL);
	                return refuse;
	            }
	        }
	    }
		private boolean Decision(String content) {
			Random ran = new Random();
			int quiero = ran.nextInt(100);
			if (quiero >= 50)
				if((content.compareTo("bebida")==0 && capacidad_bebida > 0)||(content.compareTo("comida")==0 && capacidad_comida > 0)) 
					return true;
				else
					return false;
			else 
				return false;
		}
		
		protected void takeDown(){
			DFAgentDescription template = new DFAgentDescription();
            ServiceDescription sd1 = new ServiceDescription();
            sd1.setName("Waiter");
            template.addServices(sd1);
            SearchConstraints ALL = new SearchConstraints();
            ALL.setMaxResults(new Long(-1));
            AgentContainer c = getContainerController();
            AgentController wait;
            try {
            	DFAgentDescription[] result = DFService.search(this, template, ALL);
            	for (int x=0; x<result.length; x++){
    					wait = c.getAgent(result[x].getName().getLocalName());
    					wait.kill();
    					System.out.println(getLocalName()+": buen trabajo "+result[x].getName().getLocalName());
            	}
            	System.out.println(getLocalName()+ ": GRACIAS POR VENIR A MI FIESTA");
            	DFService.deregister(this);
            }
            catch(Exception e){
            	e.printStackTrace();
            }
            
		}
}
