package bdi4jade.examples.undo.domain;

import java.io.Serializable;
import java.util.Random;

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

import jade.content.Concept;
import jade.content.ContentElement;

/**
 * @author jgfaccin
 *
 */
public class CO implements Serializable, Concept, ContentElement, Runnable {

	private static final long serialVersionUID = 2426152760359289784L;

	private static CO instance;
	private Boolean openWindows;
	private Boolean fansOn;
	private Boolean leaking;
	private Integer gasConcentration;
	private final Log log;

	private CO() {
		this.log = LogFactory.getLog(this.getClass());
		this.openWindows = false;
		this.fansOn = false;
		this.leaking = false;
		Random random = new Random(System.currentTimeMillis());
		this.gasConcentration = random.nextInt(9);
	}

	public void setOpenWindows(Boolean open) {
		this.openWindows = open;
	}

	public void setFansOn(Boolean on) {
		this.fansOn = on;
	}

	public void setLeaking(Boolean leak) {
		this.leaking = leak;
	}

	public static synchronized CO getInstance() {
		if (instance == null) {
			instance = new CO();
		}
		return instance;
	}

	public Integer getGasConcentration() {
		return this.gasConcentration;
	}

	public void updateGasConcentration() {
		if (this.leaking) {
			this.gasConcentration += 5;
			if (this.openWindows) {
				this.gasConcentration -= 3;
			} else {
				this.gasConcentration += 2;
			}
			if (this.fansOn) {
				this.gasConcentration -= 4;
			} else {
				this.gasConcentration += 3;
			}
		} else {
			if (this.openWindows) {
				if (this.gasConcentration > 9) {
					this.gasConcentration -= 3;
				}
			}
			if (this.fansOn) {
				if (this.gasConcentration > 9) {
					this.gasConcentration -= 4;
				}
			}
		}
	}

	@Override
	public void run() {
		while (true) {
			updateGasConcentration();
			log.info(this.gasConcentration);
			System.out.println("CO Concentration:" + this.gasConcentration);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
