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.examples.undo.domain.CO;
import bdi4jade.examples.undo.plan.request.RequestDeviceClosePlanBody;
import bdi4jade.examples.undo.plan.request.RequestDeviceOffPlanBody;
import bdi4jade.examples.undo.plan.request.RequestDeviceOnPlanBody;
import bdi4jade.examples.undo.plan.request.RequestDeviceOpenPlanBody;
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);

			act(requestMsg);

			this.myAgent.send(reply);
			log.info(this.myAgent.getName() + ": 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;
	}

	private void act(ACLMessage requestMsg) {
		switch (requestMsg.getContent()) {
		case RequestDeviceOnPlanBody.MSG_FANS_CONTENT:
			CO.getInstance().setFansOn(true);
			break;
		case RequestDeviceOpenPlanBody.MSG_WINDOWS_CONTENT:
			CO.getInstance().setOpenWindows(true);
			break;
		case RequestDeviceOffPlanBody.MSG_FANS_CONTENT:
			CO.getInstance().setFansOn(false);
			break;
		case RequestDeviceClosePlanBody.MSG_WINDOWS_CONTENT:
			CO.getInstance().setOpenWindows(false);
			break;
		case RequestDeviceClosePlanBody.MSG_VALVE_CONTENT:
			CO.getInstance().setLeaking(false);
		default:
			break;
		}
	}

}
