package bdi4jade.examples.undo.plan;

import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bdi4jade.annotation.Parameter;
import bdi4jade.annotation.Parameter.Direction;
import bdi4jade.plan.Plan.EndState;
import bdi4jade.plan.planbody.AbstractPlanBody;
import jade.lang.acl.ACLMessage;

/**
 * @author jgfaccin
 *
 */
public class AnswerRequestPlanBody extends AbstractPlanBody {

	private static final long serialVersionUID = -3625377753974076464L;

	private static final Log log = LogFactory.getLog(AnswerRequestPlanBody.class);
	public static final String SUCCEEDED = "SUCCEEDED";

	private ACLMessage requestMsg;

	@Override
	public void action() {
		try {
			log.info("Request received from agent " + requestMsg.getSender().getName() + "!");
			ACLMessage reply = requestMsg.createReply();
			reply.setContent(SUCCEEDED);

			Random random = new Random(System.currentTimeMillis());
			Thread.sleep(random.nextInt(10) * 1000);

			this.myAgent.send(reply);
			log.info("Reply sent to agent " + requestMsg.getSender().getName() + "!");
			setEndState(EndState.SUCCESSFUL);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Parameter(direction = Direction.IN)
	public void setMessage(ACLMessage requestMsg) {
		this.requestMsg = requestMsg;
	}

}
