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.On;
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 RequestDeviceOnPlanBody extends RevertingPlanBody {

	private static final long serialVersionUID = 6823219775966702413L;

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

	public static final String MSG_FANS_CONTENT = "FANS_ON";
	public static final String MSG_LIGHTS_CONTENT = "LIGHTS_ON";

	@bdi4jade.annotation.Belief
	private Belief<String, String> fansAgent;
	@bdi4jade.annotation.Belief
	private Belief<String, String> lightsAgent;

	private MessageTemplate mt;
	private boolean sent = false;

	@SuppressWarnings("unchecked")
	@Override
	protected void execute() {
		PredicateGoal<On> goal = (PredicateGoal<On>) this.getGoal();
		if (goal.getBeliefName().getVariable().equals(House.FANS)) {
			TransientPredicate<On> fansOn = (TransientPredicate<On>) this.getCapability().getBeliefBase()
					.getBelief(new On(House.FANS));
			manageRequest(MSG_FANS_CONTENT, fansAgent.getValue(), fansOn);
		}
		if (goal.getBeliefName().getVariable().equals(House.LIGHTS)) {
			TransientPredicate<On> lightsOn = (TransientPredicate<On>) this.getCapability().getBeliefBase()
					.getBelief(new On(House.LIGHTS));
			manageRequest(MSG_LIGHTS_CONTENT, lightsAgent.getValue(), lightsOn);
		}
	}

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

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

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

	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 + "!");
	}
}
