//----------------------------------------------------------------------------
// Copyright (C) 2011  Ingrid Nunes
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
// 
// To contact the authors:
// http://inf.ufrgs.br/prosoft/bdi4jade/
//
//----------------------------------------------------------------------------

package bdi4jade.examples.undo.plan;

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

import bdi4jade.belief.Belief;
import bdi4jade.examples.undo.domain.CO;
import bdi4jade.plan.planbody.AbstractPlanBody;
import jade.core.AID;
import jade.lang.acl.ACLMessage;

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

	private static final long serialVersionUID = 6474747389538222991L;

	private static final Log log = LogFactory.getLog(NotifyAbnormalCOPlanBody.class);
	
	private boolean lastStatus = false;

	@bdi4jade.annotation.Belief
	private Belief<String, String> managerAgent;

	public static final String ABNORMAL_CO = "ABNORMAL_CO";
	public static final String NORMAL_CO = "NORMAL_CO";
	private final String receiver = "MANAGER";
	
	@Override
	public void action() {
		while(true) {
			CO co = CO.getInstance();
			if (co.getGasConcentration() > 50 & !lastStatus) {
				notifyManager(ABNORMAL_CO);
				this.lastStatus = true;
			} else {
				if(co.getGasConcentration() <= 50 & lastStatus) {
					notifyManager(NORMAL_CO);
					this.lastStatus = false;
				}
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void notifyManager(String msgContent) {
		ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
		msg.setContent(msgContent);
		msg.addReceiver(new AID(receiver, false));
		msg.setConversationId("cin" + System.currentTimeMillis());
		myAgent.send(msg);
		log.info("Notification [" + msgContent + "] sent to agent " + receiver + "!");
	}
}
