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.belief.TransientPredicate;
import bdi4jade.examples.undo.domain.House;
import bdi4jade.examples.undo.domain.predicate.Open;
import bdi4jade.examples.undo.plan.AnswerRequestPlanBody;
import bdi4jade.extension.undo.RevertingPlanBody;
import bdi4jade.goal.PredicateGoal;
import bdi4jade.plan.Plan.EndState;
import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

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

	private static final long serialVersionUID = -3897895422901594380L;

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

	public static final String MSG_WINDOWS_CONTENT = "WINDOWS_CLOSE";
	public static final String MSG_VALVE_CONTENT = "VALVE_CLOSE";

	private MessageTemplate mt;
	private boolean sent = false;

	@bdi4jade.annotation.Belief
	private Belief<String, String> valveAgent;
	@bdi4jade.annotation.Belief
	private Belief<String, String> windowsAgent;

	@SuppressWarnings("unchecked")
	@Override
	protected void execute() {
		PredicateGoal<Open> goal = (PredicateGoal<Open>) this.getGoal();
		if (goal.getBeliefName().getVariable().equals(House.VALVE)) {
			TransientPredicate<Open> valveOpen = (TransientPredicate<Open>) this.getCapability().getBeliefBase()
					.getBelief(new Open(House.VALVE));
			manageRequest(MSG_VALVE_CONTENT, valveAgent.getValue(), valveOpen);
		}
		if (goal.getBeliefName().getVariable().equals(House.WINDOWS)) {
			TransientPredicate<Open> windowsOpen = (TransientPredicate<Open>) this.getCapability().getBeliefBase()
					.getBelief(new Open(House.WINDOWS));
			manageRequest(MSG_WINDOWS_CONTENT, windowsAgent.getValue(), windowsOpen);
		}
	}

	private void manageRequest(String msgContent, String agentName, PredicateBelief<Open> belief) {
		if (!sent) {
			sendRequest(msgContent, agentName);
		} else {
			receiveMessage(belief);
		}
	}

	private void sendRequest(String msgContent, String agentName) {
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		msg.setContent(msgContent);
		msg.addReceiver(new AID(agentName, false));
		msg.setConversationId("cin" + System.currentTimeMillis());
		myAgent.send(msg);
		this.mt = MessageTemplate.MatchConversationId(msg.getConversationId());
		this.sent = true;
		log.info("Request sent to agent " + agentName + "!");
	}

	private void receiveMessage(PredicateBelief<Open> belief) {
		ACLMessage reply = myAgent.receive(mt);
		if (reply != null) {
			if (reply.getContent().equals(AnswerRequestPlanBody.SUCCEEDED)) {
				belief.setValue(false, (PredicateGoal<Open>) this.getGoal());
				log.info(reply.getSender().getName() + ": " + reply.getContent());
				setEndState(EndState.SUCCESSFUL);
			} else {
				this.sent = false;
			}
		} else {
			block();
		}
	}

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

}
