package bdi4jade.examples.undo.plan.request;

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

import bdi4jade.belief.Belief;
import bdi4jade.belief.PredicateBelief;
import bdi4jade.examples.undo.domain.predicate.Open;
import bdi4jade.examples.undo.plan.AnswerRequestPlanBody;
import bdi4jade.extension.undo.RevertingPlanBody;
import bdi4jade.plan.Plan.EndState;
import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

/**
 * @author jgfaccin
 *
 */
public class RequestWindowsOpenPlanBody extends RevertingPlanBody {

	private static final long serialVersionUID = -349378558297777226L;

	private static final Log log = LogFactory.getLog(RequestWindowsOpenPlanBody.class);

	public static final String MSG_CONTENT = "WINDOWS_OPEN";

	private MessageTemplate mt;
	private boolean sent = false;

	@bdi4jade.annotation.Belief
	private Belief<String, String> windowsAgent;
	@bdi4jade.annotation.Belief
	private PredicateBelief<Open> windowsOpen;

	@Override
	protected void execute() {
		if (!sent) {
			ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
			msg.setContent(MSG_CONTENT);
			msg.addReceiver(new AID(windowsAgent.getValue(), false));
			msg.setConversationId("cin" + System.currentTimeMillis());
			myAgent.send(msg);
			this.mt = MessageTemplate.and(MessageTemplate.MatchConversationId(msg.getConversationId()),
					MessageTemplate.MatchInReplyTo(msg.getReplyWith()));
			this.sent = true;
			log.info("Request sent to agent " + windowsAgent.getValue() + "!");
		} else {
			ACLMessage reply = myAgent.receive(mt);
			if (reply != null) {
				if (reply.getContent().equals(AnswerRequestPlanBody.SUCCEEDED)) {
					windowsOpen.setValue(Boolean.TRUE, this.getGoal());
					log.info(reply.getSender() + ": " + reply.getContent());
					setEndState(EndState.SUCCESSFUL);
				} else {
					this.sent = false;
				}
			} else {
				block();
			}
		}
	}

	@Override
	public int onEnd() {
		this.sent = false;
		return super.onEnd();
	}

}
